Step 1, Getting the Text String Associated with the Equation:
The first step for creating an equation in VBA for word is to determine the text string associated with that equation. You might not have noticed but equations in word are a basic text string. For example take a look at the the equation below:
If you copy the equation and paste it in a notepad this is what you get:
The text in the notepad might seem like nonsense, but the word editor understands this. In order to create equations in word using VBA, we too will have the create the text string above.
The text above can be converted back to a word equation by following the steps below:
Step 1: Copy the text in the notepad editor and paste it in an empty word document:
Step 2: Select the text in the word document and click on the “Insert Equation” button on the “Insert” tab
Step 3: Choose professional View:
As you can see the equation was created from the text string in the notepad file. So basically we need to be able to generate the text string in the notepad file to create the equation in word.
I will explain this in more detail in the following sections.
The next step for creating an equation is to move the cursor to the location you want to insert the equation.For more information about moving the cursor around the document please see the links below:
Sub Example1() Dim objRange As Range Set objRange = Selection.Range objRange.Text = "y = x^2+1" Call OMaths.Add(objRange) End Sub
Note: If you want to keep reference to the newly created equation you could use the code below. You could then change the display to professional so it looks like a real equation:
Sub Example2() Dim objRange As Range Dim objOMath As OMath Set objRange = Selection.Range objRange.Text = "y = x^2+1" Set objOMath = OMaths.Add(objRange).OMaths.Item(1) objOMath.BuildUp End Sub
Creating Complex Equations:
For more complex equations you can’t simply paste the text string in the VBA editor. For example lets say we want to create the equation explained at the start of the post. The first step would be to replace the text :
Step 2: Find the unicode value associated with the missing characters. The missing characters are:
I have written a program which returns the unicode value associated with characters. You can download the program at the link below and use it to find the unicode values associated with each of the characters above: