1
votes

I am trying to build template invoices for Xero. Xero looks for specific fields in your MS Word template and inputs the variable assigned to that text field name in your given format. In word you can toggle the field code to view as just the field name:

«InvoiceNumber»

or the name with format:

{ MERGEFIELD InvoiceNumber \* MERGEFORMAT}

This outputs: INV1234 successfully into the template. Now what I need to do is output just the last 4 characters.

This post seems to imply it must be done with a VBA. I put together a macro with Visual Basic in word and this is where I have hit trouble:

Sub InvoiceNumber()
    Dim MyInv As FormFields
        Set MyInv = ActiveDocument.FormFields
        If MyInv("Text1").Result = "InvoiceNumber" Then
            MyInv("Text1").CheckBox.Value = Right(MyInv("Text1"), 4)
        End If
End Sub

This returns with

error 5941: The requested member of the selection does not exist

I am quite a beginner with VB macros in word, what am I doing wrong and how should I instead be trying to call the InvoiceNumber Field?

1

1 Answers

2
votes

Please try with the following solution:

Sub InvoiceNumber()
        Dim MyInv As Field
        Set MyInv = GetFieldByName("InvoiceNumber")

        If Not MyInv Is Nothing Then
            'do something with field result...
            'here... debug to Immediate window
            Debug.Print Right(MyInv.Result, 4)
        End If
End Sub

Function GetFieldByName(fName As String) As Field

    Dim F As Field
    For Each F In ActiveDocument.Fields
        'if not working try with (1) istead of (2) in line below
        If Split(Replace(F.Code, "  ", " "), " ")(2) = fName Then
            Set GetFieldByName = F
            Exit Function
        End If
    Next F
    Set GetFieldByName = Nothing
End Function