检查通过VBA在MS Access中访问的工作簿是否已打开

时间:2014-03-07 08:38:46

标签: vba ms-access excel-vba access-vba ms-access-2010

我使用以下代码通过VBA从Access打开工作簿。我需要检查该工作簿是否已打开:如果已打开则不执行任何操作,否则使用CreateObject方法打开它。代码如下:

Dim oAppa As Object
Dim filea As String
filea = CurrentProject.Path & "\List.xlsm"
Set oAppa = CreateObject("Excel.Application")
oAppa.Visible = True
Set owb_a = oAppa.workbooks.Open(filea, ReadOnly:=True)

在打开它时,我需要检查它是否已经打开。请帮帮我,提前致谢。

2 个答案:

答案 0 :(得分:0)

你可以遍历所有打开的工作簿,但这需要一段时间......

一个简单的解决方案,取自https://stackoverflow.com/a/9373914/2829009

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

答案 1 :(得分:0)

我刚回答了一个关于Word的几乎相同的问题。答案是相同的(或非常相似):

' Handle Error In-Line
On Error Resume Next
Set objExcel = GetObject(, "Excel.Application")

If Err.Number = 429 Then
    'If we got an error, that means there was no Excel Instance
    Set objExcel = CreateObject("Excel.Application")
Else
    Msgbox ("You're going to need to close any open Excel docs before you can perform this function.", vbOK)
    Exit Sub
End If

'Reset Error Handler
On Error GoTo 0

当然,如果实例已经存在,您可以调整您想要做的事情,而不是仅仅退出Sub。