2011-08-11 36 views
3

動態加載Excel 2010加載項時,還必須在將VBA引用加載到工作簿後將其更改爲包含新添加的加載項。可能在運行時修改Excel VBA引用(運行時加載加載項後)?

此代碼對編程加載外接:

Function LoadAddin(strFilePath As String) As Boolean 
    ' Checks whether add-in is in collection, and 
    ' then loads it. To call this procedure, pass 
    ' in add-in's path and file name. 

    Dim addXL   As Excel.AddIn 
    Dim strAddInName  As String 

    On Error Resume Next 
    ' Call ParsePath function to return file name only. 
    'strAddInName = ParsePath(strFilePath, FILE_ONLY) 'not available in VBA...so it seems to always physically load it below, which seems to work fine. 
    ' Remove extension from file name to get add-in name. 
    strAddInName = Left(strAddInName, Len(strAddInName) - 4) 
    ' Attempt to return reference to add-in. 
    Set addXL = Excel.AddIns(strAddInName) 
    If err <> 0 Then 
     err.Clear 
     ' If add-in is not in collection, add it. 
     Set addXL = Excel.AddIns.Add(strFilePath) 
     If err <> 0 Then 
     ' If error occurs, exit procedure. 
     LoadAddin = False 
     GoTo exit_function 
     End If 
    End If 
    ' Load add-in. 
    If Not addXL.Installed Then addXL.Installed = True 
    LoadAddin = True 

exit_function: 
    Exit Function 
End Function 

那麼,有沒有辦法,現在這個添加到引用,以便在主機電子表格VBA代碼,是指VBA中這個新加入的添加 - 將在正確執行?

看來,走的路線可能是這樣的:

ThisWorkbook.VBProject.References.AddFromFile ("C:\MyFiles\MyAddin.xlam") 

...但是這給我的錯誤:

Microsoft Visual Basic for Applications 
Run-time error '32813': 
Application-defined or object-defined error 
+0

如果主機項目必須在程序早期綁定引用加載,那麼你可能會得到編譯錯誤,如果沒有現有的參考:這些錯誤並不總是等到你真正調用代碼引用其他project ... –

+0

@Tim:我希望通過在Workbook_Open()中調用加載的第一件事來解決這個問題。儘管如果在電子表格打開時計算爲自動,可能會出現問題。也許可以加載一個錯誤處理程序的地方.... – tbone

+2

你有「信任訪問VBProject」選項下選中?你已經添加了對VBE擴展性庫的引用? –

回答

0

你有沒有考慮過使用相同的代碼(但略有修改)在加載項的工作簿打開事件?

如果我正確理解你,那麼我猜這就是你想要的?

Public ShouldIContinue As Boolean 

Private Sub Workbook_Open() 
    '~~> This is required to avoid the endless loop 
    If ShouldIContinue = True Then Exit Sub 

    Dim addXL As AddIn 
    Dim strAddInName As String 
    Dim oTempBk As Workbook 

    strFilePath = ThisWorkbook.FullName 

    strAddInName = ThisWorkbook.Name 
    '~~> This will work for both .xla and .xlam 
    strAddInName = Left(strAddInName, (InStrRev(strAddInName, ".", -1, _ 
    vbTextCompare) - 1)) 

    On Error Resume Next 
    Set addXL = Excel.AddIns(strAddInName) 
    On Error GoTo 0 

    If Not addXL Is Nothing Then Exit Sub 

    '~~> This is required to avoid the Run-time error '1004': 
    '~~> "Unable to get the Add property of the AddIns class" 
    '~~> OR 
    '~~> "Add method of addins class failed" 
    '~~> when there are no workbooks 
    Set oTempBk = Workbooks.Add 

    Set addXL = AddIns.Add(strFilePath, True) 
    addXL.Installed = True 

    oTempBk.Close 

    ShouldIContinue = True 
End Sub 
+0

這很可能是正確的,當我回到這個問題時,如果它解決了問題,我會回到這裏並標記爲正確。謝謝。 – tbone