运行时错误'1004':工作表类的复制方法失败

时间:2016-03-05 10:12:21

标签: vba excel-vba excel

我想通过工作表名称拆分工作簿,但是如果在拆分5张后抛出错误,但我在工作簿中有20张。我使用了以下代码,错误发生在xWs.copy。

请帮我修复代码中的错误。提前谢谢。

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

2 个答案:

答案 0 :(得分:1)

我相信你队列中有一个隐藏的工作表。在下文中,我已存储原始Worksheet.Visible property值(XlSheetVisibility Enumeration),然后使工作表可见并最终恢复原始可见性状态。如果它已经开始可见,则没有错误。

我从不建议您在Workbook.SaveAs 操作中包含文件扩展名。实际上,我建议有意省略它并允许 FileFormat 参数和XlFileFormat Enumeration提供正确的文件扩展名。

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

如果要跳过不可见的工作表,请添加一个条件,如果xWs.Visible属性不是 xlSheetVisible ,则不执行Copy,SaveAs操作。

如果工作表代码表中有代码(例如Worksheet_Change事件宏),由于Application.DisplayAlerts你必须 False ,它将被丢弃而不确认。

答案 1 :(得分:0)

看起来您正在分割的工作簿被激活,并且因为它包含宏,所以它不能保存为xlsx。

尝试在Application.EnableEvents = False之前和周期For Each xWs In ThisWorkbook.Sheets之后添加Application.EnableEvents = True