简体   繁体   English

Excel VBA将多个工作簿中的多个工作表合并到一个工作簿中

[英]excel vba merge multiple sheets from multiple workbooks into one workbook

I have two excel workbooks and I need to take a set of sheets from one and a set of sheets form another and save it as a new workbook. 我有两个Excel工作簿,我需要从一个工作簿中取出一组工作表,然后从另一个工作表中取出一组工作表,并将其另存为新工作簿。 Since I will be doing this weekly, I would like to save it as a macro/vba. 由于本周将进行此操作,因此我想将其另存为宏/ vba。

I found this code online and edited it, but it is not working. 我在网上找到了此代码并对其进行了编辑,但无法正常工作。

Sub CopySheets()
    Dim wkb As Workbook
    Dim sWksName As String

sWksName = "Store 1"
For Each wkb In Workbooks
    If wkb.Name <> ThisWorkbook.Name Then
        wkb.Worksheets(sWksName).Copy _
          Before:=ThisWorkbook.Sheets(1)
    End If
Next
Set wkb = Nothing

    sWksName = "Store 3"
For Each wkb In Workbooks
    If wkb.Name <> ThisWorkbook.Name Then
        wkb.Worksheets(sWksName).Copy _
          Before:=ThisWorkbook.Sheets(1)
    End If
Next
Set wkb = Nothing

    sWksName = "Store 30"
For Each wkb In Workbooks
    If wkb.Name <> ThisWorkbook.Name Then
        wkb.Worksheets(sWksName).Copy _
          Before:=ThisWorkbook.Sheets(1)
    End If
Next
Set wkb = Nothing

    sWksName = "Store 33"
For Each wkb In Workbooks
    If wkb.Name <> ThisWorkbook.Name Then
        wkb.Worksheets(sWksName).Copy _
          Before:=ThisWorkbook.Sheets(1)
    End If
Next
Set wkb = Nothing


End Sub

I have to have both workbooks open, which is no problem. 我必须打开两个工作簿,这没问题。 The sheet "Store 1" gets copied fine and then it stops and when I click on debug, it tells me that there is an error with this line 工作表“ Store 1”被很好地复制,然后停止,当我单击“ debug”时,它告诉我此行存在错误

 wkb.Worksheets(sWksName).Copy _
              Before:=ThisWorkbook.Sheets(1)

Error message: "Script out of range" 错误消息:“脚本超出范围”

Sub CopySheets()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim sWsNames As String

    sWsNames = "Store 1,Store 3,Store 30,Store 33"

    For Each wb In Workbooks
        If wb.Name <> ThisWorkbook.Name Then
            For Each ws In wb.Sheets
                If InStr(1, "," & sWsNames & ",", "," & ws.Name & ",", vbTextCompare) > 0 Then
                    ws.Copy Before:=ThisWorkbook.Sheets(1)
                End If
            Next ws
        End If
    Next

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM