[英]Automation error or Error 462 in excel VBA code
我在 Excel VBA 中使用以下代碼時收到錯誤“-2147417848 (80010108) 運行時錯誤”:
sub import()
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.ScreenUpdating = False
On Error GoTo error
Dim App As New excel.Application
Dim wbImport As Workbook
Set wbImport = App.Workbooks.Open(ThisWorkbook.Path & "\" & "example.xlsm")
'DATA COPY
Dim Lastrow As Integer
Lastrow = ThisWorkbook.Worksheets("DATA").Cells(Rows.Count, 1).End(xlUp).Row
ThisWorkbook.Worksheets("DATA").Range("A2:AM" & Lastrow).Copy
wbImport.Worksheets("DATA").Range("a2").PasteSpecial Paste:=xlPasteValues
wbImport.Worksheets("CONFIG").Shapes("pdv").Visible = False
wbImport.Close SaveChanges:=True
App.CutCopyMode = False
App.Quit
MsgBox "OK"
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
error:
App.CutCopyMode = False
wbImport.Close SaveChanges:=True
App.Quit
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
MsgBox "FAIL"
End sub
最近發現,通過添加
Set App = Nothing
后
App.Quit
它給了我“錯誤 462”,但我不知道為什么。 調試只是正常運行,錯誤提示在最后,在msgboxes之后。
我確定這不是最好的解決方案,但我發現的是:
1-無需將應用程序調暗為Dim App As New excel.Application
即可在后台打開 excel 文件。
在打開之后和之前屏幕更新屬性足以不顯示該過程:
Application.ScreenUpdating = False
Dim wbImport As Workbook
Set wbImport = Workbooks.Open(ThisWorkbook.Path & "\example.xlsm"
Application.ScreenUpdating = True
2-我忘了在“錯誤:”句柄之前添加Exit sub
。
最終代碼:
sub import()
On Error GoTo error
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim wbImport As Workbook
Set wbImport = App.Workbooks.Open(ThisWorkbook.Path & "\" & "example.xlsm")
'DATA COPY
Dim Lastrow As Integer
Lastrow = ThisWorkbook.Worksheets("DATA").Cells(Rows.Count, 1).End(xlUp).Row
ThisWorkbook.Worksheets("DATA").Range("A2:AM" & Lastrow).Copy
wbImport.Worksheets("DATA").Range("a2").PasteSpecial Paste:=xlPasteValues
wbImport.Worksheets("CONFIG").Shapes("pdv").Visible = False
wbImport.Close SaveChanges:=True
MsgBox "OK"
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
exit sub
error:
wbImport.Close SaveChanges:=True
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
MsgBox "FAIL"
End sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.