2016-10-11 41 views
0

在MS Outlook中,我有一個調用MS Access宏的按鈕。該宏打開表單並設置文本。每次如果我按下該按鈕,Access的新實例正在打開。如何防止打開多個Access實例?如何防止Outlook中的.Run打開兩次Access實例?

展望代碼:

'general declarations: 
Public appAccess As Object 


Sub OpenRecord() 
    Dim Reference As String 
    Dim docAccess 

    Reference = 'teststring' 

    Set appAccess = CreateObject("Access.Application") 
    docAccess = appAccess.opencurrentdatabase("D:\Database\MSA_db.accdb") 
    appAccess.Visible = True 
    appAccess.Run "OpenInternalReference", Reference 
End Sub 

接入碼:

Public Sub OpenInternalReference(MailReference As String) 
    Dim stDocName As String 
    Dim stLinkCriteria As String 

    stDocName = "browse" 
    DoCmd.OpenForm stDocName, , , stLinkCriteria 

    Forms("Browse").prefilter.SetFocus 
    Forms("Browse").prefilter.Text = MailReference 
End Sub 

回答

2

你的問題不是.Run方法,它是你的Set appAccess = CreateObject("Access.Application"),因爲它始終會進入一個新的實例。

此代碼試圖獲得一個已經打開Access應用程序中,如果沒有被發現,創建一個新的:

Dim appAccess As Object 

On Error Resume Next 
Set appAccess = GetObject(Class:="Access.Application") 
On Error GoTo 0 

If appAccess Is Nothing Then 
    Set appAccess = CreateObject("Access.Application") 
End If 
+0

我不得不添加唯一的辦法就是一個'上的錯誤恢復Next'上面的'opencurrentdatabase'命令。 – Jellema

+0

@Jellema如果你添加了On Error Resume Next,那麼你還必須添加On Error Goto 0.否則我們必須在Peer Review中收取一個錯誤。 – niton

+0

@niton:好的,我會用它 – Jellema