【问题标题】:Is there an Excel VBA function for checking whether another Excel file is actively saving?是否有用于检查另一个 Excel 文件是否正在保存的 Excel VBA 功能?
【发布时间】:2019-06-05 17:44:42
【问题描述】:

是否有可用于检查 Excel 文件是否正在保存的 VBA 代码?

我在 Excel 文件(文件 A)中使用 VBA 宏打开另一个 Excel 文件(文件 B)。

DummyDirectory="C:\DummyFolder1\DummyFolder2\"

Workbooks.Open filename:=DummyDirectory & "DummyFile.xlsb", ReadOnly:=True

如果文件 B 正在被其他人主动保存,当我在文件 A 中运行宏时,我会收到运行时错误 (1004)。在尝试使用文件 A 中的宏打开文件 B 之前,我想检查文件 B 是否正在被其他人主动保存。

我不希望使用基于运行时错误 1004 的错误处理,因为其他原因可能会发生此错误。

【问题讨论】:

  • 此检查毫无意义,因为有人可能会在您的检查告诉您文件未保存后立即开始主动保存文件。你必须处理错误。

标签: excel vba


【解决方案1】:

没有。

确实,发生错误 1004 的原因有很多种。但是在这里:

Workbooks.Open filename:=DummyDirectory & "DummyFile.xlsb", ReadOnly:=True

假设 filename 参数是合法的,那么该行抛出的错误 1004 意味着“Excel 无法保存文件” - 您看不到实际原因,因为“文件当前被另一个用户写锁定”错误被 Excel 捕获、处理、包装并作为一个非常有用的“应用程序定义的错误”呈现给 VBA。

事实是,实际的错误根本不重要 - VBA 需要知道的是 Workbooks.Open 失败。

处理错误,并尽可能限制错误处理的范围。一种方法是将指令放在它自己的函数中(aircode,未经测试):

Public Function TryOpenWorkbookReadOnly(ByVal filename As String, ByRef outBook As Workbook) As Boolean
    On Error Resume Next
    Set outBook = Workbooks.Open filename, ReadOnly:=True
    On Error GoTo 0
    TryOpenWorkbookReadOnly = (Err.Number = 0)
End Function

现在你可以使用标准控制流了:

Dim book As Workbook
If Not TryOpenWorkbookReadOnly(DummyDirectory & "DummyFile.xlsb", outBook:=book) Then
    MsgBox "Could not open the file. Try again later."
    Exit Sub
End If

'go on, use the book object as needed:
'...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 2015-08-02
    • 2013-03-06
    • 1970-01-01
    • 2014-11-05
    相关资源
    最近更新 更多