Excel 仅当特定工作簿处于打开状态时,才在关闭前调用工作簿_下的宏
我已将此代码放入我的PERSONAL.xlsb:Excel 仅当特定工作簿处于打开状态时,才在关闭前调用工作簿_下的宏,excel,vba,Excel,Vba,我已将此代码放入我的PERSONAL.xlsb: Sub CheckInMsg() MsgBox "Reminder! Save and Check In this workbook when you are done.", vbInformation, "Closing Reminder" End Sub 从该工作簿中,可以从以下位置调用它: Private Sub Workbook_BeforeClose(Cancel As Boolean) Call DeleteFrom
Sub CheckInMsg()
MsgBox "Reminder! Save and Check In this workbook when you are done.", vbInformation, "Closing Reminder"
End Sub
从该工作簿中,可以从以下位置调用它:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call DeleteFromCellMenu
Call DeleteMasterMenu
Call CheckInMsg
End Sub
但我希望此代码仅在特定工作簿(MasterFile.xlsm)打开时运行。我不知道如何做到这一点。这是否需要在关闭子项之前添加到工作簿中?或者在CheckInMsg sub中?如果您能提供任何帮助,我们将不胜感激。在您的
工作簿\u BeforeClose()
事件中,您可以循环浏览所有打开的工作簿,如果您找到了要查找的名称,则可以执行三个调用。比如:
Dim wb As Workbook
For Each wb In Application.Workbooks
If wb.Name = "MasterFile.xlsm" Then
Call DeleteFromCellMenu
Call DeleteMasterMenu
Call CheckInMsg
End If
Next
您可以创建一个函数:
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function
然后在代码中使用它:
If IsFileOpen("c:\Book2.xls") Then
'do stuff
End If
如果您不想使用该函数,可以将此代码实现到sub中。这看起来正是我需要的。但是,我可以在DIM语句之前运行两个调用(Call DeleteFromCellMenu和Call DeleteMasterMenu)吗?我想你会把这段代码放到我在这本手册里的私人密码里吗?是的。您只想在工作簿打开时执行的任何操作都会进入For/If块。如果无论工作簿处于打开状态,都希望执行某些操作,请将其粘贴到For/If块之外。此外,是的,这将在关闭(取消为布尔值)之前进入您的
私有子工作簿子例程。我想,您也可以将For/If块粘贴到其他子例程中,并将msgbox()
调用放在其中。它会在你需要的地方工作。非常灵活。谢谢你的帮助。信息量大,回答了问题的各个方面。这很有效。