可能在运行时修改Excel VBA引用(运行时加载一个加载项后)?

在dynamic加载Excel 2010加载项时,还必须在将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 

那么现在有什么办法可以把这个添加到引用中,所以在这个新包含的Add-In中引用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 

您是否考虑过在加载项的Workbook打开事件中使用相同的代码(但稍加修改)?

如果我正确理解你,那么我猜这就是你想要的?

 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