检测Excel工作簿是否已经打开。

12 浏览
0 Comments

检测Excel工作簿是否已经打开。

已关闭。这个问题需要更加专注。目前不接受回答。


想要改进这个问题吗? 通过编辑这个帖子来让问题专注于一个问题。

改进这个问题

在VBA中,我通过编程方式打开了名为“myWork.XL”的MS Excel文件。

现在我想要一个代码,可以告诉我它的状态 - 它是否已经打开。 比如像 IsWorkBookOpened(\"myWork.XL) ?

admin 更改状态以发布 2023年5月21日
0
0 Comments

在我的应用程序中,我通常希望使用工作簿而不仅仅是确定它是否打开。对于这种情况,我更喜欢跳过布尔函数并直接返回工作簿。

Sub test()
    Dim wb As Workbook
    Set wb = GetWorkbook("C:\Users\dick\Dropbox\Excel\Hoops.xls")
    If Not wb Is Nothing Then
        Debug.Print wb.Name
    End If
End Sub
Public Function GetWorkbook(ByVal sFullName As String) As Workbook
    Dim sFile As String
    Dim wbReturn As Workbook
    sFile = Dir(sFullName)
    On Error Resume Next
        Set wbReturn = Workbooks(sFile)
        If wbReturn Is Nothing Then
            Set wbReturn = Workbooks.Open(sFullName)
        End If
    On Error GoTo 0
    Set GetWorkbook = wbReturn
End Function

0
0 Comments

试试这个:

Option Explicit
Sub Sample()
    Dim Ret
    Ret = IsWorkBookOpen("C:\myWork.xlsx")
    If Ret = True Then
        MsgBox "File is open"
    Else
        MsgBox "File is Closed"
    End If
End Sub
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

0