[英]Attempting to clear the values in two cells in a different workbook when I close the workbook. Run-time 91 error
I'm attempting to clear the values in two cells in a different workbook when I close the workbook I'm actively using. 当我关闭我正在使用的工作簿时,我正试图清除不同工作簿中两个单元格中的值。 When I close my workbook I receive the following error:
当我关闭我的工作簿时,我收到以下错误:
Run-time error '91': Object variable or With block variable not set
运行时错误'91':对象变量或未设置块变量
Using debug and stepping through I can find the line where I receive the error but for the life of me I'm not seeing what I'm missing. 使用调试和单步执行我可以找到我收到错误的行,但对于我的生活,我没有看到我缺少的东西。
I call my macro from: 我打电话给我的宏:
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
Try to run the following code until you can do it without an error: 尝试运行以下代码,直到您可以执行它而不会出现错误:
Sub TestClear()
Dim SourceWb As Workbook
Dim myWS As Worksheet
Set SourceWb = ThisWorkbook
Set myWS = SourceWb.Worksheets("Sheet1")
Debug.Print myWS.Name
End Sub
Probably the error is in the way you use SourceWb
or you do not have Sheet1
. 可能错误在于您使用
SourceWb
的方式,或者您没有Sheet1
。
You are victim of a re-entrant, theoretically never-ending routine. 你是一个可重入的,理论上永无止境的例程的牺牲品。 Without disabling events , inside
Workbook_BeforeClose
, you call ThisWorkbook.Close
which will again cause Workbook_BeforeClose
to be invoked, then again and again. 在没有禁用事件的情况下 ,在
Workbook_BeforeClose
,调用ThisWorkbook.Close
,这将再次调用Workbook_BeforeClose
,然后一次又一次地调用。 This causes undefined behavior (probably a StackOverfow !) 这会导致未定义的行为 (可能是StackOverfow !)
Quick-fix: disable events: 快速修复:禁用事件:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.EnableEvents = False '<------- To avoid re-entance
On Error Resume Next
TestClear
Application.EnableEvents = True
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.