我的以下代码遇到问题:
Private Sub Worksheet_BeforeDoubleClick(ByVal...
Application.ScreenUpdating = False
Set wbks = Workbooks.Open("\\whatever\whatever.xlsx")
wbks.Sheets("Control").Activate
ActiveSheet.Range("A3").Select
Application.ScreenUpdating = True
...
如您所见,每次我双击某个单元格时,它都会打开一个工作簿。 问题是:第二次双击后,我收到了烦人的消息:
“'Filename.xlsx'已打开。重新打开将导致您所做的任何更改被丢弃...”
如何关闭此消息(因为没有进行任何更改),并且如果可能的话,使目标工作簿在每次双击后“更新”而不是“重新打开”?
最佳答案
您可以使用函数来检查它是否已经打开:
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
code>,稍微扩展一下上面的逻辑:
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
关于excel - 如何 "update"工作簿而不是重新打开它(使用 VBA 宏)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16825538/