Late binding an Object in VBA

2019-07-29 22:27发布

问题:

I am getting the "run-time error 429" in my attempt at late binding to the VBProject object:

Dim vbProj As Object
Set vbProj = CreateObject("ActiveDocument.VBProject")

Is there something fundamental I am failing to understand?

For example, how would you write the code in article 308340 to use late binding?:

 Sub CheckReference()

        Dim vbProj As VBProject  
        Set vbProj = ActiveDocument.VBProject

        For Each chkRef In vbProj.References

          If chkRef.IsBroken Then
             Debug.Print chkRef.Name
          End If

        Next

    End Sub

回答1:

Dennis,

if you are running this from within Word, then you don't need to use CreateObject().

Set vbProj = ActiveDocument.VBProject will work.

if you are running this from elsewhere, then you may need to create Word object first and load the document:

  Dim a As Object
  Dim vbProj As Object

  Set a = CreateObject("Word.Application")
  a.Documents.Open "C:\temp\test1.docx"
  MsgBox a.Documents.Count
  Set vbProj = a.ActiveDocument.VBProject

In both cases you may get the "Programmatic Access to Visual Basic Project is not Trusted" which resolves through Macro security settings, http://support.microsoft.com/kb/282830.

I hope this answers your question.



回答2:

Where did you come up with that progid (ActiveDocument.VBProject)? Generally progid's are of the form AppName.ObjectName, as in Excel.Sheet or Word.Document. IIRC, VB6 doesn't support OLE Automation itself; rather, it supports creating OLE Automation servers and clients.

Update:

Ok, I see what's going on now. ActiveDocument.VBProject isn't a valid progid. ActiveDocument is a property of the Word.Application object, which has a progid of (surprise!) "Word.Application".

So you want Meringros answer.