试图在closures工作簿时清除不同工作簿中两个单元格中的值。 运行时91错误

当我closures正在使用的工作簿时,我试图清除不同工作簿中两个单元格中的值。 当我closures我的工作簿时收到以下错误:

运行时错误“91”:对象variables或块variables未设置

使用debugging和步进通过我可以find我收到错误的行,但对于我的生活,我没有看到我失踪。

我打电话给我的macros:

Private Sub Workbook_BeforeClose(Cancel As Boolean) TestClear End Sub Sub TestClear() Application.ScreenUpdating = False Application.DisplayAlerts = False Dim SourceWb As Workbook, myWS As Worksheet Set SourceWb = Workbooks.Open("Workbook file location, in this case it's on a network share") Set myWS = SourceWb.Sheets("Sheet1") <---- Here is where I receive the Run-Time error '91' myWS.Range("A1").Clear myWS.Range("B1").Clear SourceWb.Close SaveChanges:=1 ThisWorkbook.Close SaveChanges:=1 Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub 

你是一个重新进入,理论上永无止境的例程的受害者。 如果不禁用事件 ,则在Workbook_BeforeClose调用ThisWorkbook.Close ,这将再次导致Workbook_BeforeClose被调用,然后一次又一次。 这会导致未定义的行为 (可能是一个StackOverfow !)

快速修复:禁用事件:

 Private Sub Workbook_BeforeClose(Cancel As Boolean) Application.EnableEvents = False '<------- To avoid re-entance On Error Resume Next TestClear Application.EnableEvents = True End Sub 

尝试运行下面的代码,直到你可以做到没有错误:

 Sub TestClear() Dim SourceWb As Workbook Dim myWS As Worksheet Set SourceWb = ThisWorkbook Set myWS = SourceWb.Worksheets("Sheet1") Debug.Print myWS.Name End Sub 

可能错误是你使用SourceWb的方式,或者你没有Sheet1