我仍在学习VBA,所以这可能是一个愚蠢的问题,但我希望浏览〜90-95张纸的工作簿,将它们分成自己的工作簿,并将其另存为原始文件中工作表的名称。
该脚本有效,但仅当我注释掉.Worksheets(1).Delete时,我才想知道为什么...它在我对其运行的两个工作表上均抛出1004错误,但在同一地点。第一张工作表在选项卡4上出现错误,第二张工作表在40号上出现错误。
现在,我已经设置了FileNamePrefix变量以进行切换,因为我正在VBA窗口中的“ ThisWorkbook”下运行此变量,因为我还没有弄清楚如何从自己的工作表中运行此宏,并且根据文件名/扩展名选择前缀。 (AC以.xlsm出现,CC以.xlsx出现)这仍然是我的工作,所以请不要破坏我! :)
宏:
Sub Sheet_SaveAs()
Dim wb As Workbook
Dim WS_Count As Integer
Dim ActiveSheetName As String
Dim ws As Worksheet
Dim FileNamePrefix As String
Dim FileName As String
Dim FilePath As String
'FileNamePrefix = "CC Dashboard "
FileNamePrefix = "AC Dashboard "
WS_Count = ActiveWorkbook.Worksheets.Count
MsgBox (" This will create: " & WS_Count & " Files")
For Each ws In ThisWorkbook.Worksheets
Set wb = Workbooks.Add(xlWBATWorksheet)
With wb
ThisWorkbook.Worksheets(ws.Name).Copy After:=.Worksheets(.Worksheets.Count)
Application.DisplayAlerts = False
.Worksheets(1).Delete
Application.DisplayAlerts = True
.SaveAs ThisWorkbook.Path & "\" & FileNamePrefix & ws.Name
.Close False
End With
ws.Name = FileNamePrefix & ws.Name
Next
MsgBox (" Done! ")
End Sub
答案 0 :(得分:1)
因此,让我们摆脱Delete(删除),仅使用所需的工作表创建新文件。我还对您的代码做了一些清理。
Sub Sheet_SaveAs()
Dim wb As Workbook
Dim WS_Count As Integer
Dim ActiveSheetName, FileNamePrefix, FileName, FilePath As String
Dim ws As Worksheet
'FileNamePrefix = "CC Dashboard "
FileNamePrefix = "AC Dashboard "
WS_Count = ActiveWorkbook.Worksheets.Count
MsgBox (" This will create: " & WS_Count & " Files")
For Each ws In ThisWorkbook.Worksheets
ws.Copy 'this creates a new file with only the one sheet, so no Delete needed
ActiveWorkbook.SaveAs ThisWorkbook.Path & "\" & FileNamePrefix & ws.Name
ActiveWorkbook.Close False
Next
MsgBox (" Done! ")
End Sub