(Solved) – Assign Word Object to Variant Variable in VBA


My aim is to create an array of various global templates which I define in a table. My macro reads the table. If the name specifies an available template my array should hold the object. If the template can’t be found the array should hold the name that couldn’t be processed. ThisDocument is of docm type. It’s assigned to Sfs(0) as the default. Here is an excerpt from my code.

Private Sub TestSetSfs()
    Dim Sfs() As Variant
    SetSfs Sfs
End Sub

Function SetSfs(Sfs() As Variant) As Long
    ReDim Sfs(20)
    Set Sfs(0) = ThisDocument

    Debug.Print VarType(Sfs(0)), vbString, vbObject
    Debug.Print Sfs(0).Bookmarks.Exists(LnMsg)
End Function

My problem is with the line Set Sfs(0) = ThisDocument. Instead of the ThisDocument object the object’s name is assigned. Vartype(Sfs(0)) in the next line returns 8 = vbString. However, in the last line of the text procedure Sfs(0) works correctly as an object. It’s also shown as an object in the Locals window.

As you see, Sfs() is declared outside the procedure where it gives the problem. In that procedure all elements (including element 0 and others, not included in this demonstration) are of VarType vbString and shown as such in the Locals window.

Let me add that I already have this idea working in Excel (with addins) but I need an equivalent in Word where I think the global template would meet my requirements if I could assign objects to the Sfs() variant. Any idea how to do that?

Leave a Reply

Your email address will not be published. Required fields are marked *