【问题标题】:Macro check if a file is open, including open as Read-only宏检查文件是否打开,包括以只读方式打开
【发布时间】:2021-08-11 05:08:03
【问题描述】:

我正在使用下面的 VBA 宏函数来检查文件是否已经打开。但是,它错过了文件以只读方式打开的情况。

你们能否建议应该在代码中添加什么?

Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long

On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0

Select Case ErrNo
Case 0:    IsWorkBookOpen = False
Case 70:   IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function

【问题讨论】:

标签: excel vba readonly


【解决方案1】:

Excel 帮助的一个非常好的地方是https://www.excelforum.com/

Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long

On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
ErrNo = Err
On Error GoTo 0

If IsFileLocked(FileName) = True Then
'Do stuff - Report and exit if true, etc
End If
Close ff

Select Case ErrNo
Case 0:    IsWorkBookOpen = False
Case 70:   IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function

Function IsFileLocked(strFileName As String) As Boolean
  On Error Resume Next
  Open strFileName For Binary Access Read Write Lock Read Write As #1
  Close #1
  IsFileLocked = Err.Number
  Err.Clear
End Function

答案来自: https://www.mrexcel.com/board/threads/vba-to-tell-if-file-is-read-only.965985/

【讨论】:

    猜你喜欢
    • 2010-12-10
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多