VBA: Run-Time Automation Error - “Code execution has been interrupted”

痞子三分冷 提交于 2020-01-15 12:05:16

问题


I'm attempting to write a program to loop through a directory of excel files and copy a range into a "Master Workbook". When I run the program I am prompted with "Code execution has been interrupted". If I select continue the code will successfully run but then a "run-time error '-2147221080' Automation error" appears.

The line that causes the error is:

 Set ws = wb.Worksheets("Project Log")

My question is, why is this line causing the error and or is there a way to bypass the error prompt so that my code will successfully run?

 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

回答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

You might want to check for the ForecastFileName being False, that is when the users x's out, you will also want to do a little validation the wb sheet is in the right format by checking column headers ect or you will wind up crashing.



来源:https://stackoverflow.com/questions/48176775/vba-run-time-automation-error-code-execution-has-been-interrupted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!