将来自不同文件中的多个工作表的数据导入到单个工作簿中

时间:2018-05-29 08:52:53

标签: excel-vba vba excel

我正在尝试将数据从多个工作簿(由“文件选择器”对话框选择的Excel文件)导入到一个工作簿中。 每个工作簿包含3个工作表,工作簿和工作表源以及工作簿和工作表目标具有相同的结构。 如果我选择一个文件,代码已经工作,但如果我选择2个或更多文件,则不会将结果复制到目标表中。 我尝试了不同的解决方案,但vba代码对我来说是新的,我无法弄清楚出了什么问题。 有人能说出代码有什么问题吗?

//*[@text()='Please upload this owner's ID:']

1 个答案:

答案 0 :(得分:0)

尝试这种方式。

更改此代码行中的范围

'填写您要复制的范围 设置CopyRng = sh.Range(“ A1:G1”)

Sub CopyRangeFromMultiWorksheets()
    Dim sh As Worksheet
    Dim DestSh As Worksheet
    Dim Last As Long
    Dim CopyRng As Range

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Delete the sheet "RDBMergeSheet" if it exist
    Application.DisplayAlerts = False
    On Error Resume Next
    ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    'Add a worksheet with the name "RDBMergeSheet"
    Set DestSh = ActiveWorkbook.Worksheets.Add
    DestSh.Name = "RDBMergeSheet"

    'loop through all worksheets and copy the data to the DestSh
    For Each sh In ActiveWorkbook.Worksheets
        If sh.Name <> DestSh.Name Then

            'Find the last row with data on the DestSh
            Last = LastRow(DestSh)

            'Fill in the range that you want to copy
            Set CopyRng = sh.Range("A1:G1")

            'Test if there enough rows in the DestSh to copy all the data
            If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                MsgBox "There are not enough rows in the Destsh"
                GoTo ExitTheSub
            End If

            'This example copies values/formats, if you only want to copy the
            'values or want to copy everything look at the example below this macro
            CopyRng.Copy
            With DestSh.Cells(Last + 1, "A")
                .PasteSpecial xlPasteValues
                .PasteSpecial xlPasteFormats
                Application.CutCopyMode = False
            End With

            'Optional: This will copy the sheet name in the H column
            DestSh.Cells(Last + 1, "H").Resize(CopyRng.Rows.Count).Value = sh.Name

        End If
    Next

ExitTheSub:

    Application.Goto DestSh.Cells(1)

    'AutoFit the column width in the DestSh sheet
    DestSh.Columns.AutoFit

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub

https://www.rondebruin.nl/win/s3/win002.htm