您可以使用一個函數來檢查它是否已經打開:
Function WorkbookIsOpen(wb_name As String) As Boolean
On Error Resume Next
WorkbookIsOpen = CBool(Len(Workbooks(wb_name).Name) > 0)
End Function
然後在你的程序中,這樣稱呼它:
Private Sub Worksheet_BeforeDoubleClick(ByVal...
Application.ScreenUpdating = False
If WorkbookIsOpen("whatever.xlsx") then
Set wbks = Workbooks("whatever.xlsx")
Else
Set wbks = Workbooks.Open("\\whatever\whatever.xlsx")
End If
wbks.Sheets("Control").Activate
ActiveSheet.Range("A3").Select
Application.ScreenUpdating = True
編輯:如果你真的要發瘋了,您可以使用此功能檢查文件是否存在,如果不存在則返回Nothing
,否則返回Workbook
,在上面的邏輯中略微擴展:
Function GetWorkbook(WbFullName As String) As Excel.Workbook
'checks whether workbook exists
'if no, returns nothing
'if yes and already open, returns wb
'if yes and not open, opens and returns workbook
Dim WbName As String
WbName = Mid(WbFullName, InStrRev(WbFullName, Application.PathSeparator) + 1)
If Not WorkbookIsOpen(WbName) Then
If FileExists(WbFullName) Then
Set GetWorkbook = Workbooks.Open(Filename:=WbFullName, UpdateLinks:=False, ReadOnly:=True)
Else
Set GetWorkbook = Nothing
End If
Else
Set GetWorkbook = Workbooks(WbName)
End If
End Function
除了上述WorkbookIsOpen
功能,它使用此一:
Function FileExists(strFileName As String) As Boolean
If Dir(pathname:=strFileName, Attributes:=vbNormal) <> "" Then
FileExists = True
End If
End Function
你可以在你的程序中使用,如:
Private Sub Worksheet_BeforeDoubleClick(ByVal...
Application.ScreenUpdating = False
Set wbks = GetWorkbook("\\whatever\whatever.xlsx")
If wbks is Nothing Then
MsgBox "That's funny, it was just here"
'exit sub gracefully
End If
wbks.Sheets("Control").Activate
ActiveSheet.Range("A3").Select
Application.ScreenUpdating = True
看看這個[鏈接](HTTP:// stackoverflow.com/questions/16777311/vba-stock-in-workbook-open-continues-if-i-press-f5/16782098#16782098) – Santosh