VBA动态加载引用
这两天抽空写了些VBA脚本,遇到一个Case,需要将Excel中的内容导出到Word中。正常情况下,需要加工程里手动添加引用。Google一番后,找到了一种无需手动添加额外引用的办法:https://stackoverflow.com/a/42228424
Sub AddReferences(wbk As Workbook)
' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub
Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
Dim i As Integer
On Error GoTo EH
With wbk.VBProject.References
For i = 1 To .Count
If .Item(i).Name = sRefName Then
Exit For
End If
Next i
If i > .Count Then
.AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
End If
End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
Resume EX
Resume ' debug code
End Sub
Public Sub DebugPrintExistingRefs()
Dim i As Integer
With Application.ThisWorkbook.VBProject.References
For i = 1 To .Count
Debug.Print " AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
Next i
End With
End Sub
最终稍作修改:
Private Sub AddWordReferences()
Dim vbProj As Object: Set vbProj = ActiveWorkbook.VBProject
With vbProj.References
For i = 1 To .Count
If .Item(i).Name = "Word" Then
Exit For
End If
Next i
If i > .Count Then
.AddFromGuid "{00020905-0000-0000-C000-000000000046}", 0, 0 ' 0,0 should pick the latest version installed on the computer
End If
End With
Debug.Print "-----After add reference-----"
With vbProj.References
For i = 1 To .Count
Debug.Print .Item(i).Name
Next i
End With
End Sub
- Author: Half Stack
- Link: https://zhangsn.me/VBA-add-reference-in-runtime/
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.