我有一个带有一些数据透视表的Excel文件,该文件具有一个宏,该宏可以打开Excel SOURCE文件,更新不同的数据透视表,最后它应该关闭源文件。如果我评论FOR循环,它将正确打开和关闭SOURCE文件,因此我怀疑循环中存在问题。
谢谢您的任何建议
Option Explicit
Private Sub Workbook_Open()
Call aggiorna
End Sub
Sub aggiorna()
On Error GoTo ErrHandler
Application.ScreenUpdating = False
Dim wrb As Workbook
Dim pt As PivotTable
' Apre in sola lettura
Set wrb = Workbooks.Open("C:\Users\Saila\Desktop\Ore Operatori_2018.xlsx", True, True)
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
Next pt
' Chiude Sorgente
wrb.Close
Set wrb = Nothing
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:1)
代码很可能在数据透视表循环期间引发了一些错误,然后跳转到ErrHandler:
标签,从而跳过了wrb.Close
和Set wrb = Nothing
将后面的这些语句移到ErrHandler:
标签之后
Sub aggiorna()
On Error GoTo ErrHandler
Application.ScreenUpdating = False
Dim wrb As Workbook
Dim pt As PivotTable
' Apre in sola lettura
Set wrb = Workbooks.Open("C:\Users\Saila\Desktop\Ore Operatori_2018.xlsx", True, True)
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
Next pt
ErrHandler:
' Chiude Sorgente
wrb.Close
Set wrb = Nothing
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
顺便说一句,您可能想注释On Error GoTo ErrHandler
,查看代码失败的原因和原因,然后增强代码以适当地管理错误