调试宏合并多个工作簿

时间:2014-04-29 16:42:27

标签: excel-vba vba excel

我尝试在.csv文件上使用以下宏,目的是将多个工作簿中的所有数据合并到一个工作簿中的一个工作表中。

Sub cons_data()

Dim Master As Workbook
Dim sourceBook As Workbook
Dim sourceData As Worksheet
Dim CurrentFileName As String
Dim myPath As String
Dim LastRow As Long
Dim lRow As Long
Dim i As Long

Application.ScreenUpdating = False
Application.DisplayAlerts = False

'The folder containing the files to be recap'd
myPath = "C:\FakePath"

'Finds the name of the first file of type .csv in the current directory
CurrentFileName = Dir(myPath & "\*.csv*")

'Create a workbook for the recap report
Set Master = ThisWorkbook

For i = 1 To Master.Worksheets.Count
    With Master.Worksheets(i)
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        If lRow > 1 Then .Rows("2:" & lRow).ClearContents
    End With
Next i

Do
    Workbooks.Open (myPath & "\" & CurrentFileName)
    Set sourceBook = Workbooks(CurrentFileName)
    For i = 1 To sourceBook.Worksheets.Count
        Set sourceData = sourceBook.Worksheets(i)

        With sourceData
            LastRow = Master.Worksheets(.Name).Range("A" & Rows.Count).End(xlUp).Row
            lRow = .Range("A" & .Rows.Count).End(xlUp).Row
            .Rows("2:" & lRow).Copy Master.Worksheets(.Name).Rows(LastRow + 1)
        End With
    Next i

    sourceBook.Close

'Calling DIR w/o argument finds the next .csv file within the current directory.
CurrentFileName = Dir()
Loop While CurrentFileName <> ""

MsgBox "Done"

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

但是,我在下一行收到错误(如果有人知道在上面添加行号会非常感激):

 LastRow = Master.Worksheets(.Name).Range("A" & Rows.Count).End(xlUp).Row

即,我收到错误&#34;运行时错误&#39; 9&#39;:下标超出范围&#34;。

通常我会被提示打开一个文件夹并能够选择所有想要的书籍,但由于某种原因这种情况不会发生。

1 个答案:

答案 0 :(得分:1)

您收到的下标超出范围错误,因为您的主工作簿中没有与csv文件同名的工作表。

请记住,当您在Excel中打开csv文件时,它只有一个工作表,该表的名称是csv文件的名称(没有文件扩展名)。