簡體   English   中英

VBA:運行時自動化錯誤-“代碼執行已中斷”

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

我正在嘗試編寫一個程序以遍歷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
   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不在時,您還需要通過檢查列標題ect來對wb表的格式正確進行一點驗證,否則將崩潰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM