合并来自多个Excel工作簿的命名工作表,仅复制一次标题,源范围是可变的



下面是我目前正在尝试运行的代码。代码工作正常,但标题是从每个工作表复制的,并且从下一个文件复制数据的位置之间的行数存在显着差距。例如,第一个文件有 3600 行,下一个数据在第 13,000 行中复制。任何建议将不胜感激。

Sub MergeAllWorkbooks()
    Dim SummarySheet As Worksheet
    Dim FolderPath As String
    Dim NRow As Long
    Dim FileName As String
    Dim WorkBk As Workbook
    Dim SourceRange As Range
    Dim DestRange As Range
    Dim LastRow As Long
    ' Create a new workbook and set a variable to the first sheet.
    Set SummarySheet = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    ' Modify this folder path to point to the files you want to use.
    FolderPath = "C:DesktopFiles to Combine"
    ' NRow keeps track of where to insert new rows in the destination workbook.
    NRow = 1
    ' Call Dir the first time, pointing it to all Excel files in the folder path.
    FileName = Dir(FolderPath & "*.xl*")
    ' Loop until Dir returns an empty string.
    Do While FileName <> ""
        ' Open a workbook in the folder
        Set WorkBk = Workbooks.Open(FolderPath & FileName)

        ' Set the source range to be A1 through BH and the last row.
        ' Modify this range for workbooks.
    LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
    Set SourceRange = WorkBk.Worksheets(1).Range("A1:BH" & LastRow)
        ' Set the destination range to start at column A and
        ' be the same size as the source range.
        Set DestRange = SummarySheet.Range("A1" & NRow)
        Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
           SourceRange.Columns.Count)
        ' Copy over the values from the source to the destination.
        DestRange.Value = SourceRange.Value
        ' Increase NRow so that we know where to copy data next.
        NRow = NRow + DestRange.Rows.Count
        ' Close the source workbook without saving changes.
        WorkBk.Close savechanges:=False
        ' Use Dir to get the next file name.
        FileName = Dir()
    Loop
    ' Call AutoFit on the destination sheet so that all
    ' data is readable.
    SummarySheet.Columns.AutoFit
End Sub

对于行计数问题,请注意@ScottHoltzman的评论。另一个问题是大量单元格可能是空的,但仍在使用范围内,因为只清理了它们的内容,但格式仍然存在。您可能需要从工作簿中删除此类单元格,而不仅仅是清除内容。

为避免重复标头,请将第一个文件设置为引入标头,并将所有其他文件从第 2 行开始。

i = 1                            ' INITIALIZE AN INT/LONG VARIABLE
Do While FileName <> ""
    '...
    If i = 1 Then
       Set SourceRange = WorkBk.Worksheets(1).Range("A1:BH" & LastRow)
    Else
       Set SourceRange = WorkBk.Worksheets(1).Range("A2:BH" & LastRow)
    End If
    '...
    i = i + 1                    ' INCREMENT VARIABLE
    FileName = Dir()
Loop

最新更新