Is it possible to use VBA functions in Word field codes?
Asked Answered
Z

1

6

I have a Word document with some functions. I want to access these functions in formula fields, but this was harder than anticipated.

Let's say I have a function defined as

Public Function Area(R As Double) As Double
  Area = 3.14 * R * R
End Function

and that I want to use this in a field, like this

{ = Area(RadiusBookmark) }

This seems pretty straight forward, but I get a syntax error. If I omit the parameter, like this

{ = Area }

I get an "undefined bookmark" error, which leads me to believe that only bookmarks are available to the formula code fields.

Zebulun answered 7/9, 2016 at 8:34 Comment(0)
I
2

Word doesn't allow you to use VBA functions in a field.

One common approach is to use a field with a DocVariable, and have some VBA that is triggered by a button press or a document event, that sets the value of the variable to the result of a function, and then refreshes the field value.

First, add a DOCVARIABLE field to your document:

My function returns ‘DOCVARIABLE MyFuncResult \* MERGEFORMAT’!

Then add this VBA:

Option Explicit

Private Function Foo() As String
  Foo = "BAR"
End Function

Public Sub setvar()

  Const MYVAR As String = "MyFuncResult"

  Dim var As Variable

  On Error Resume Next
  Set var = ThisDocument.Variables(MYVAR)
  On Error GoTo 0

  If var Is Nothing Then
    Set var = ThisDocument.Variables.Add(MYVAR)
  End If

  var.Value = Foo

  ThisDocument.Fields.Update

End Sub

And you should see the document content as:

My function returns ‘BAR’!

Indult answered 18/9, 2016 at 8:39 Comment(1)
Seems worthwhile to note that .Variables("somename").Value = "somevalue" will implicitly invoke the .Add method if you're inputting a variable name that hasn't been created yet. So Sub setvar() in this example would be functionally equivalent if it were simply written as: ThisDocument.Variables("MyFuncResult").Value = Foo : ThisDocument.Fields.UpdateParamedic

© 2022 - 2024 — McMap. All rights reserved.