Calculate method Word Add-in VBA (Visual Basic for Applications)

Calculate method Word Add-in VBA (Visual Basic for Applications)

Calculate

Surprisingly excel is built for mostly calculations because of the data stored in it. But Microsoft Word also provide basic calculations which can be performed in a range or selection. Calculate is a method which calculates a mathematical expression within a selection. Returns the result as a Single.

Example

Refer above example where I have written simple equation and the highlighted text has bookmark which I have created to make a boundary so the result can be populated within as shown below:

I have used two bookmarks ResultStart and ResultEnd which will build a placeholder to hold the result. Let’s write code to achieve result of above equation.

Public Sub CalculateResult()
    'Grabe Selection
    Dim oRange As Range
    Set oRange = Selection.Range
    
    'Bind bookmark
    Dim oResult As Range
    Set oResult = ThisDocument.Range(ThisDocument.Bookmarks("ResultStart").Start, ThisDocument.Bookmarks("ResultEnd").Start)
    
    'calculate the result an put in placeholder
    oResult.Text = oRange.Calculate
End Sub

Output

Note: you have to select equation before running the code because Calculation will be performed on selection which we are binding in a Range object in the code above.

Leave a Reply

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