您好我正在尝试使用此代码将每张Excel保存到新工作簿。但是,它将整个工作簿保存为新文件名
Dim path As String
Dim dt As String
dt = Now()
path = CreateObject("WScript.Shell").specialfolders("Desktop") & "\Calendars " & Replace(Replace(dt, ":", "."), "/", ".")
MkDir path
Call Shell("explorer.exe" & " " & path, vbNormalFocus)
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If ws.name <> "How-To" And ws.name <> "Actg_Prd" Then
ws.SaveAs path & ws.name, xlsx
End If
Next ws
什么是快速解决方案?
答案 0 :(得分:12)
将工作表保留在现有工作簿中并使用副本创建新工作簿
Dim path As String
Dim dt As String
dt = Now()
path = CreateObject("WScript.Shell").specialfolders("Desktop") & "\Calendars " & Replace(Replace(dt, ":", "."), "/", ".")
MkDir path
Call Shell("explorer.exe" & " " & path, vbNormalFocus)
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If ws.Name <> "How-To" And ws.Name <> "Actg_Prd" Then
Dim wb As Workbook
Set wb = ws.Application.Workbooks.Add
ws.Copy Before:=wb.Sheets(1)
wb.SaveAs path & ws.Name, Excel.XlFileFormat.xlOpenXMLWorkbook
Set wb = Nothing
End If
Next ws
答案 1 :(得分:0)
我建议引入一些错误检查,以确保您最终尝试将工作簿保存到的文件夹实际存在。这也将创建相对于保存启用宏的Excel文件的位置的文件夹。
On Error Resume Next
MkDir ThisWorkbook.path & "\Calendars\"
On Error GoTo 0
我强烈建议在保存后立即关闭新创建的工作簿。如果您正在尝试创建大量新工作簿,您将很快发现它滞后于您的系统。
wb.Close
此外,Sorceri的代码不会使用适当的文件扩展名保存excel文件。您必须在文件名中指定。
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If ws.Name <> "How-To" And ws.Name <> "Actg_Prd" Then
Dim wb As Workbook
Set wb = ws.Application.Workbooks.Add
ws.Copy Before:=wb.Sheets(1)
wb.SaveAs path & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
wb.Close
Set wb = Nothing
End If
Next ws