如何使用VBA将多个Excel文件中的数据合并到一个主文件中?

时间:2018-12-14 13:01:23

标签: excel vba excel-vba

我有多个文件,并带有数据示例 所有文件看起来都与图片中的文件相同

image 这是我的主文件结构 Master

这是我的代码,

   Sub Append()
'Append data from other files
 Path = "E:\NPM PahseIII\"
 Dim c As Range
  'find the second empty cell in ColA
 Set c = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(2, 0)
  Filename = Dir(Path & "*.xlsx")
     Do While Filename <> ""
If InStr(Filename, ".") > 0 Then
     Filenamenoext = Left(Filename, InStr(Filename, ".") - 1)
End If

 c.Value = Filenamenoext
   Set c = c.Offset(1, 0)

 Workbooks.Open Filename:=Path & Filename, ReadOnly:=True

ThisWorkbook.Activate
ActiveSheet.Range("B3:E6").Select
 Selection.Consolidate Sources:=Array("'" & Path & "[" & Filename & 
 "]Sheet1'!B3:B6")

Workbooks(Filename).Close
Filename = Dir()
Loop

End Sub

运行此代码后,我的主文件变成这个 enter image description here

从第二张图片中我们可以看到,只有文件名写在主文件中,但数据没有与其他文件合并,我在这一问题上呆了一整天,不知道我的代码有什么问题, 其次,我希望如果我再次运行此代码,就不会重复,那么该数据就不必复制了,因为当前正在复制数据,因为当我再次运行该代码时,文件名将从上一个记录的底部开始再次写入。 为了合并来自其他文件的数据并且不执行重复操作,我当前的代码可能是什么问题?

1 个答案:

答案 0 :(得分: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

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