如何使用动态范围将具有相同结构的不同工作簿合并为一个

时间:2018-11-12 13:00:16

标签: excel vba excel-vba

我有多个工作簿,每个工作簿都具有相同的结构,希望将它们合并到一个工作簿中,在网络上找到了一些示例,但无法实现我想要的代码,我将创建合并,但是只选一列。我想从一个点开始复制整个使用范围,例如“ A2”已经尝试了几次,这是我尝试过的内容,这是我尝试过的内容,没有任何建议,欢迎您

Sub Trymerge()
Dim FolderPath As String, Path As String, count As Integer
Dim ThisWB As String, lngFilecounter As Long
Dim wbDest As Workbook, shtDest As Worksheet, ws As Worksheet
Dim Filename As String, Wkb As Workbook
Dim CopyRng As Range, Dest As Range
Dim RowofCopySheet As Integer

ThisWB = ActiveWorkbook.Name

FolderPath = "H:\Staging\Testmerge"

' path = FolderPath & "\*.xls*"

'Filename = Dir(path)
Filename = Dir(FolderPath & "\*.xls*", vbNormal)
MsgBox Filename
RowofCopySheet = 11

Application.EnableEvents = False
Application.ScreenUpdating = False

Set shtDest = ActiveWorkbook.Sheets(1)

Do While Filename <> ""
MsgBox Filename
   count = count + 1
   If Not Filename = ThisWB Then
    Set Wkb = Workbooks.Open(Filename:=FolderPath & "\" & Filename)
    MsgBox "working file" & Filename
   Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(Cells(Rows.count, 1).End(xlUp).Row, Cells(1, Columns.count).End(xlToLeft).Column))
   'Wkb.Sheets(1).Range("A11").Select
    ' Set CopyRng = Wkb.Sheets(1).Range(RowofCopySheet, ActiveCell.End(xlDown).End(xlToRight))
    'Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(.UsedRange.Rows.count, .UsedRange.Columns.count))
    Set Dest = shtDest.Range("A" & shtDest.Cells(Rows.count, 1).End(xlUp).Row + 1)
    CopyRng.Copy
    Dest.PasteSpecial xlPasteFormats
    Dest.PasteSpecial xlPasteValuesAndNumberFormats
    Application.CutCopyMode = False 'Clear Clipboard
    Wkb.Close False
End If
    Filename = Dir()
Loop

' Range("Q8").Value = count
 MsgBox count & " : files found in folder"
 End Sub

3 个答案:

答案 0 :(得分:1)

这是我用来遍历文件夹,从所有文件中复制数据,然后将数据保存到其他位置的组合电子表格中的脚本。您需要将myPath更改为文件夹的路径,将i变量更改为所需的范围,并将j变量更改为合并的电子表格的位置/范围。

Sub CombineReports()

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim i As Long
Dim j As Long

'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.CutCopyMode = False

'Target Folder Path For Macro
myPath = "I:\Pricing\mt access\Tier Reports\Final Reports\"

'In Case of Cancel
myPath = myPath
If myPath = "" Then GoTo ResetSettings

'Loop through each Excel file in folder
myFile = Dir(myPath)
Do While myFile <> ""

'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
DoEvents

'Count rows in your spreadsheet and set range to copy
i = wb.Worksheets(1).Range("A" & Rows.Count).End(xlUp).Row
wb.Worksheets(1).Range("A5", "N" & i).Copy

    'Combine data from each spreadsheet into one main sheet
    With Workbooks.Open("I:\Pricing\mt access\Tier Reports\Final Reports\Combined Report\CombinedTierReport.xlsx")
    DoEvents
    j = Workbooks("CombinedTierReport.xlsx").Worksheets("AllStores").Range("B" & Rows.Count).End(xlUp).Row
    Workbooks("CombinedTierReport.xlsx").Worksheets("AllStores").Range("A" & j + 1).PasteSpecial xlPasteValues
    Workbooks("CombinedTierReport.xlsx").Save
    Workbooks("CombinedTierReport.xlsx").Close
    End With
    DoEvents

'Save and Close Workbook
Application.DisplayAlerts = False
wb.Close SaveChanges:=False
Application.DisplayAlerts = True
DoEvents

'Get next file name
myFile = Dir
Loop

'Reset Macro Optimization Settings
ResetSettings:
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.CutCopyMode = True

End Sub

答案 1 :(得分:0)

如果您的代码已经可以使用,则可以如下更改代码:

您拥有的代码:

Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(Cells(Rows.count, 1).End(xlUp).Row, Cells(1, Columns.count).End(xlToLeft).Column))

您可以通过更改复制范围来使其更简单:

假设A列到达工作表的底部,假设第一行到达工作表的最后一列

Dim LastRow As Long
Dim LastCol As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row 
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(LastRow, LastCol))

使用此功能,CopyRng将占用整个范围,而不仅仅是最后一列。

答案 2 :(得分:0)

您可以轻松地合并文件夹中所有工作簿中的数据(彼此之间)。

Sub Basic_Example_1()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next

                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A1:C1")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all columns then skip this file
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "Sorry there are not enough rows in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in column A
                        With sourceRange
                            BaseWks.cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.Range("B" & rnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

如果由于某种原因,您想要进行合并并且将数据集水平而不是垂直排列,则可以使用下面的脚本。

Sub Basic_Example_3()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceCcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim Cnum As Long, CalcMode As Long

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    Cnum = 1

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next
                Set sourceRange = mybook.Worksheets(1).Range("A1:A10")

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all rows then skip this file
                    If sourceRange.Rows.Count >= BaseWks.Rows.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceCcount = sourceRange.Columns.Count

                    If Cnum + SourceCcount >= BaseWks.Columns.Count Then
                        MsgBox "Sorry there are not enough columns in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in the first row
                        With sourceRange
                            BaseWks.cells(1, Cnum). _
                                    Resize(, .Columns.Count).Value = MyFiles(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.cells(2, Cnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        Cnum = Cnum + SourceCcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With

End Sub