VBA:运行时自动化错误 - “代码执行已被中断”
Posted
技术标签:
【中文标题】VBA:运行时自动化错误 - “代码执行已被中断”【英文标题】:VBA: Run-Time Automation Error - "Code execution has been interrupted" 【发布时间】:2018-06-18 23:52:40 【问题描述】:我正在尝试编写一个程序来循环遍历 excel 文件的目录并将一个范围复制到“主工作簿”中。当我运行程序时,系统会提示我“代码执行已被中断”。如果我选择继续,代码将成功运行,但会出现“运行时错误'-2147221080'自动化错误”。
导致错误的行是:
Set ws = wb.Worksheets("Project Log")
我的问题是,为什么这条线会导致错误,或者有没有办法绕过错误提示,以便我的代码能够成功运行?
Sub FileCompiler()
Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
Dim Masterwb As Workbook
Dim ws as Worksheet
'set workbook in which data will be copied to
Set Masterwb = ActiveWorkbook
'declare path
'folderPath = "C:MyPath\"
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
'compile directory data to master spreadsheet
Filename = Dir(folderPath & "*.xls*")
Do While Filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & Filename)
Set ws = wb.Worksheets("Project Log")
ws.Range(ws.Cells(2, "C"), ws.Cells(2, "C")).Copy
Masterwb.Worksheets("Staging").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial
ws.Range(ws.Cells(7, "A"), ws.Cells(Rows.Count, "K").End(xlUp)).Copy
Masterwb.Worksheets("Staging").Range("B" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial
wb.Close True
Filename = Dir
Loop
Application.ScreenUpdating = True
End Sub
【问题讨论】:
如果没有具有该名称的工作表,您会看到该错误。该工作表是否存在于每个工作簿中?仅供参考,您在那里连续有两个ws.Range(...).Copy
- 第一行将无效。此外,您不会更改打开的工作簿,因此您可以使用 wb.Close False
@TimWilliams 该错误通常会导致缺少工作表吗?如果我尝试访问不存在的工作表,我通常会收到 Subscript Out of Range Error 9
类型错误。尝试访问未打开的工作簿中的工作表时,似乎会弹出此报告的错误代码。但是他的代码在打开工作簿时不会抛出错误(所以它应该是打开的)。例如,如果您 Set wb = Workbooks.Open... wb.Close Set ws = wb.Worksheets("Sheet1")
您会收到引用的错误。
也可以添加Dim ws as Worksheet
当它因错误而中断时,工作簿是否打开,并且是否有一个具有该名称的工作表?很容易检查...
^^^^ 将您的 ws 声明为工作表。它可能必须处于活动状态才能设置它。你不必担心你的主人在活动时已经设置了它。
【参考方案1】:
Dim Finfo As String
Dim FilterIndex As Long
Dim Title As String
Dim CopyBook As Workbook
Dim CopySheet As Worksheet
Dim ForecastFileName As Variant
Dim MasterSheet AS Worksheet
Set MasterSheet = ThisWorkbook.Worksheets("Yoursheetname")
'now you can always use master sheet after you set copybook
'Set up file filter
Finfo = "Excel Files (*.xls*),*.xls*"
'Set filter index to Excel Files by default in case more are added
FilterIndex = 1
' set Caption for dialogue box
Title = "Hey there!, select a file"
'get the Forecast Filename
ForecastFileName = Application.GetOpenFilename(Finfo, FilterIndex, Title)
'Change this according to what you need for workbook and worksheet names
Workbooks.Open (ForecastFileName)
Set CopyBook = ActiveWorkbook
Set CopySheet = CopyBook.Worksheets(1)
'Do your code, remember to close
CopyBook.Close savechanges:=False 'Not needed now
您可能想要检查 ForecastFileName 是否为 False,即当用户 x 退出时,您还需要通过检查列标题等来验证 wb 表的格式是否正确,否则您将崩溃.
【讨论】:
以上是关于VBA:运行时自动化错误 - “代码执行已被中断”的主要内容,如果未能解决你的问题,请参考以下文章
解决 Excel VBA 文本文件导出中的运行时 91 错误