在单独的文件中复制工作表

时间:2019-06-10 15:08:07

标签: excel vba

我正在尝试将工作表拆分为多个文件。我一直在使用下面的代码没有问题。然后今天它只是停止运行时错误-方法工作表类的复制失败。

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

下面的代码有效!

Sub Splitbook()

Dim varResponse As Variant

varResponse = MsgBox("Each new worksheet will be saved as a new file within the current folder. Would you like to create new files using each worksheet now?", vbYesNo, "Selection")
If varResponse <> vbYes Then Exit Sub

'Updateby20140612
Dim xPath As String
Dim wb As Workbook

Set wb = ActiveWorkbook

xPath = Application.ActiveWorkbook.path
Application.ScreenUpdating = False
Application.DisplayAlerts = False

For Each xWs In ThisWorkbook.Sheets
    Set newbook = Workbooks.Add
    xWs.Copy before:=newbook.Sheets(1)
    newbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xlsx"
    newbook.Close False
    Set newbook = Nothing
Next

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    MsgBox "New workbooks successfully created."
End Sub

1 个答案:

答案 0 :(得分:2)

应该是这样(未经测试):

For Each xWs In ThisWorkbook.Sheets
    set newBook = workbooks.add
    xWs.Copy before:=newBook.sheets(1)
    newBook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xlsx"
    newBook.Close False
    set newBook = Nothing
Next xWs