我有一个工作簿,在打开时会创建另一个空白工作簿,可能会将一些数据复制到其中。我想在关闭工作簿时测试创建的工作簿是否仍处于打开状态。
我在一张空白工作簿上测试了这个。对于“ThisWorkbook”'代码我有
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Refreshwkbk Is Nothing Then
MsgBox "other wkbk closed"
Else
MsgBox "other wkbk open"
Refreshwkbk.Activate
End If
End Sub
Private Sub Workbook_Open()
Call myRefresh
End Sub
在我有一个模块中
Public Refreshwkbk As Workbook
Sub myRefresh()
Set Refreshwkbk = Workbooks.Add
End Sub
代码将在Refreshwkbk.Activate
处中断并出现自动化错误
错误为Run-time error '-2147221080 (800401a8)'
我如何测试新创建的工作簿是否仍处于打开状态?
答案 0 :(得分:2)
最简单的方法是尝试.Activate
它,如果它抛出错误,它已经关闭。
Private Sub Workbook_BeforeClose(Cancel As Boolean)
On Error GoTo WKBK_CLOSED
Refreshwkbk.Activate 'if that fails it jumps to WKBK_CLOSED
MsgBox "other wkbk open"
Exit Sub
WKBK_CLOSED:
MsgBox "other wkbk closed"
End Sub
答案 1 :(得分:0)
使用对象可能有更好的方法,但是这是一种循环遍历所有打开的工作簿的方法。
Dim wb As Workbook
'looping through currently opened workbooks
For Each wb In Workbooks
If wb.Name = refreshwkbk.Name Then
refreshwkbk.Activate
MsgBox "other wkbk open"
Else
If refreshwkbk Is Nothing Then
MsgBox "other wkbk closed"
End If
End If
Next wb