Connect references (Tools>References) with VBA code (macros)

≡放荡痞女 提交于 2021-02-04 12:43:07

问题


I want to programmatically connect some references to my VBA project using VBA code, i.e. without manually setting references using Tools>References. Is this possible? For example Microsoft office 12.0 Object library.


回答1:


You do not mention an Office application. In MS Access, you can use:

ReferenceFromFile "C:\Program Files\Common Files\Microsoft Shared\OFFICE14\MSO.DLL"

That is, give the full path for the reference you wish to add.

From: http://wiki.lessthandot.com/index.php/Add,_Remove,_Check_References

Similarly, in Excel:

ActiveWorkbook.VBProject.References.AddFromFile "C:\Program Files\Common Files\Microsoft Shared\OFFICE14\MSO.DLL"

To list references in Excel: Dim ref As Reference

For Each ref In ActiveWorkbook.VBProject.References
    Debug.Print ref.Description; " -- "; ref.FullPath
Next

This returns the following on my machine on one particular workbook:

Visual Basic For Applications -- C:\PROGRA~1\COMMON~1\MICROS~1\VBA\VBA7\VBE7.DLL
Microsoft Excel 14.0 Object Library -- C:\Program Files\Microsoft Office\Office14\EXCEL.EXE
OLE Automation -- C:\Windows\system32\stdole2.tlb
Microsoft Forms 2.0 Object Library -- C:\Windows\system32\FM20.DLL
Microsoft ActiveX Data Objects 6.0 Library -- C:\Program Files\Common Files\System\ado\msado15.dll
Microsoft XML, v6.0 -- C:\Windows\System32\msxml6.dll
Microsoft Office 14.0 Access database engine Object Library -- C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEDAO.DLL
Microsoft Visual Basic for Applications Extensibility 5.3 -- C:\Program Files (x86)\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB
Microsoft Office 14.0 Object Library -- C:\Program Files\Common Files\Microsoft Shared\OFFICE14\MSO.DLL



回答2:


Making references to the full path is fraught with danger and will cause you problems when the code is used on different computers or in different versions.

Far better to use the GUID which in most (but not all instances) remains the same for different versions of an application.

This is helpful especially if you've written code for say Excel 2010 that needs to be used in both Excel 2010 and Excel 2013.




回答3:


There is an alternate location where the MSO.dll file can be found:

C:\Program Files (x86)\Common Files\microsoft shared\oFFICE11

Just set the Tool > References >Browse to the above path and locate MSO.dll



来源:https://stackoverflow.com/questions/10730300/connect-references-toolsreferences-with-vba-code-macros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!