问题
I want to split workbook by worksheet name but if throws above error after splitting 5 sheets but i have 20 sheets in the workbook. I have used below code and the error happens at xWs.copy.
Please help me fix the error in the code. Thanks in advance.
Sub Splitbook()
'Updateby20140612
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
回答1:
I believe you have a hidden worksheet in the queue. In the following, I've stored the original Worksheet.Visible property value (XlSheetVisibility Enumeration), then made the worksheet visible and finally restored the original visiblility state. If it was already visible to begin with, there is no error.
I never recommend that you include a file extension in a Workbook.SaveAs operation. In fact, I recommend intentionally omitting it and allowing the FileFormat parameter and XlFileFormat Enumeration to supply the correct file extension.
Sub Splitbook()
Dim vis As Long, xPath As String, xWs As Worksheet
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
vis = xWs.Visible
xWs.Visible = xlSheetVisible
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name, _
FileFormat:=xlOpenXMLWorkbook
Application.ActiveWorkbook.Close False
xWs.Visible = vis
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
If you want to skip worksheets that are not visible, add a condition that does not perform the Copy, SaveAs operation if the xWs.Visible property is not xlSheetVisible.
If there is code in the worksheet code sheet (e.g. a Worksheet_Change event macro), it will be discarded without acknowledgement due to the Application.DisplayAlerts you have to False.
回答2:
It looks like the workbook you are splitting gets activated, and because it contains macros it couldn't be saved as xlsx.
Try to add Application.EnableEvents = False before your For Each xWs In ThisWorkbook.Sheets and after the cycle Application.EnableEvents = True
来源:https://stackoverflow.com/questions/35812806/run-time-error-1004-copy-method-of-worksheet-class-failed