excel - 如何 "update"工作簿而不是重新打开它(使用 VBA 宏)?

标签 excel vba

我的以下代码遇到问题:

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/

相关文章:

sql - 如何在SQL中实现Excel COMBIN函数

excel - 用于排除列标题从 Access 2007 传输到 Excel 2007 的代码

excel - 如何使用 Power Query 删除行内的重复项?

ms-access - 除非处于 Shift 键旁路模式,否则不会显示进度条

vba - 在 Excel 文件中的现有内容之后传输 Access 2010 结果表

vba - Excel VBA 集合不断重复最后一个对象

python - 使用 Pandas 引用下一行值

excel - 通过 CommandButton 取消选中整个工作簿中的所有复选框

vba - Excel 2013 VBA 为单个工作簿打开多个窗口

vba - 列表框在 Excel VBA 中无法正确返回数据