下划线超出范围>>> total = Workbooks(“Summary File.xls”)。Worksheets.Count

时间:2016-10-04 12:55:46

标签: vba excel-vba excel

Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Double
Application.ScreenUpdating = False
Application.DisplayAlerts = False

directory = "c:\test\"
fileName = Dir(directory & "*.xl??")

Do While fileName <> ""
Workbooks.Open (directory & fileName)
For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("Summary File.xls").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
    after:=Workbooks("Summary File.xls").Worksheets(total)
Next sheet
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

1 个答案:

答案 0 :(得分:0)

我想这是因为&#34;摘要File.xls&#34;是Excel 97-2003格式,并且您尝试在其中插入来自更新的Excel版本文件的工作表,这些文件具有更多的列和行,从而导致错误,其结果是&#34;摘要文件&#34;关闭并随后尝试引用它(即Workbooks("Summary File.xls")),抛出&#34;下标超出范围&#34;错误

更改您的&#34;摘要文件&#34;至少2007年的Excel版本(从头开始,否则尝试使用另存为将生成仍会抛出该错误的兼容模式),然后运行您的宏

BTW,在Workbooks(fileName).Worksheets(sheet.Name)循环中用sheet替换For Each sheet In Workbooks(fileName).Worksheets