将Excel文件合并到主文件(VBA)

时间:2016-12-01 15:05:27

标签: excel vba excel-vba

有人可以看看我的代码并告诉我我做错了什么吗?我正在尝试将一组文件夹中的Excel文件合并到一个主Excel文件中。我的逻辑似乎是正确的,但由于某种原因,数据不会从源文件粘贴到主文件中。提前谢谢大家!

Sub ConsolidateMAR()
'
'
'
   Dim lastRow As Long

   Dim MyFolder As String

   Dim myFile As String

   Dim wbkSource As Workbook


   Dim wkbDest As Workbook

   Set wkbDest = Workbooks.Open("C:\Users\xxxxx\Desktop\MAR Test Master File.xlsx")

On Error Resume Next

Application.ScreenUpdating = False



With Application.FileDialog(msoFileDialogFolderPicker)

.Title = "Please select a folder"

.Show

.AllowMultiSelect = False

   If .SelectedItems.Count = 0 Then 'If no folder is selected, abort

MsgBox "You did not select a folder"

      Exit Sub

   End If

MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder

End With

myFile = Dir(MyFolder) 'DIR gets the first file of the folder

'Loop through all files in a folder until DIR cannot find anymore

Do While myFile <> “”

   'Opens the file and assigns to the wbkSource variable for future use

   Set wbkSource = Workbooks.Open(FileName:=MyFolder & myFile)

   'Replace the line below with the statements you would want your macro to perform

If Err.Number <> 0 Then
        MsgBox ("Unable to open file " & myFile)
    End If
    On Error GoTo 0


wbkSource.ActiveSheet.Unprotect Password:="adgiam"

Columns.EntireColumn.Hidden = False
    Rows.EntireRow.Hidden = False
    Rows("3:3").Select
    Selection.AutoFilter

    Rows("3:3").Select
    Selection.AutoFilter


    lastRow = wbkSource.ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row

    Range("A4:W" & lastRow).Select

    Selection.Copy

    Application.DisplayAlerts = False

    erow = wkbDest.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

    wkbDest.ActiveSheet.Paste Destination:=Sheets(1).Range(Cells(erow, 1), Cells(erow, 23))


wbkSource.Close SaveChanges:=False

myFile = Dir 'DIR gets the next file in the folder

Loop

wkbDest.Close SaveChanges:=True

Application.ScreenUpdating = True

MsgBox "Macro has completed! Woot! Woot!"

End Sub

2 个答案:

答案 0 :(得分:0)

我必须做类似的事情,但选择将工作表移动到新的工作簿中。 见So, I have 6 "master" files to then divide into 40 separate files

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

另外,请查看下面的AddIn。

http://www.rondebruin.nl/win/addins/rdbmerge.htm