Problem : Can’t Remove Broken VBA Project Reference Using VBA

Problem : Can’t Remove Broken VBA Project Reference Using VBA

I am trying to remove a broken VBA project reference using VBA so that I can add the currently available reference. The broken reference is in the VBProject.References collection but when I use the Remove method I get the error “Object library not registered.” When I try to add the correct library I get the error “Name conflicts with existing module, project, or object library.” I can’t use late binding as the broken library causes VBA functions such as Trim to stop working.

The libraries I am trying to delete/add are “Microsoft Word 9.0 Object Library” and “Microsoft Word 10.0 Object Library.” Here is code that illustrates this problem. In this case the workbook has a broken reference to “Microsoft Word 10.0 Object Library” and I want to delete that reference and add a reference to the “Microsoft Word 9.0 Object Library:”

Const TargetReferenceGUID = “{00020905-0000-0000-C000-000000000046}” ‘ Microsoft Word x.x Object Library

Dim TargetReference As Object
Dim ReferenceIndex As Long
Dim Index As Long

‘ Find existing reference
For Index = 1 To ThisWorkbook.VBProject.References.Count
If ThisWorkbook.VBProject.References(Index).GUID = TargetReferenceGUID Then
ReferenceIndex = Index
Exit For
End If
Next Index

‘ Delete existing reference
If ReferenceIndex > 0 Then
ThisWorkbook.VBProject.References.Remove ThisWorkbook.VBProject.References(Index)
End If

‘ Add desired reference
ThisWorkbook.VBProject.References.AddFromGuid TargetReferenceGUID, 8, 1 ‘ Microsoft Word 9.0 Object Library

To aid those willing to help me I have uploaded a workbook (http://www.geocities.com/zorvek/Library-Reference-Problem.xls) created using Office XP (Excel 2002), which has a reference to “Microsoft Word 10.0 Object Library,” and contains the above code. When opened on a system running Office 2000 (“Microsoft Word 9.0 Object Library” versus “Microsoft Word 10.0 Object Library”) it exhibits the above problems.

 

Solution : Can’t Remove Broken VBA Project Reference Using VBA

Could You test the following approach:

Option Explicit

Sub Delete_Broken_References()
‘#1 Add a reference to the library Microsoft Visual Basic for Applications Extensibility 5.3’via Tools | References… in
‘     the VB-editor.

‘#2 The procedure needs to be inside another workbook and  the target workbook must be open before executing it.

Dim VBReferens As VBIDE.Reference
Dim VBProjekt As VBIDE.VBProject
Dim stBok As String

stBok = Workbooks(“Test.xls”).Name

Set VBProjekt = Workbooks(stBok).VBProject

For Each VBReferens In VBProjekt.References
If VBReferens.IsBroken Then VBProjekt.References.Remove VBReferens
Next VBReferens

End Sub

I’m off now (too late as usual…) but will check in tomorrow my local time.