我已将此代码放入我的PERSONAL.xlsb:
Sub CheckInMsg()
MsgBox "Reminder! Save and Check In this workbook when you are done.", vbInformation, "Closing Reminder"
End Sub
来自ThisWorkbook,来自:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call DeleteFromCellMenu
Call DeleteMasterMenu
Call CheckInMsg
End Sub
但是我希望这个代码只在特定工作簿打开时运行(MasterFile.xlsm)。我不知道如何实现这一目标。这是否需要添加到Workbook_BeforeClose子中?或者在CheckInMsg子中?非常感谢任何帮助。
答案 0 :(得分:3)
在Workbook_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
答案 1 :(得分:-1)
您可以创建一个功能:
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
如果您不想使用功能,可以将此代码实现到子目录中。