Using VBA for Word to insert a lot of mixed text and equations

Per Strömdahl 1 Reputation point
2022-10-22T15:42:36.143+00:00

Hello! I'm a complete beginner to programming in VBA for Word, but I would like to use VBA in Word to mix equations and text. I read the documentation at https://learn.microsoft.com/en-us/office/vba/api/word.omath , but the problem is that when I try to use Selection.TypeText to write normal text after the equation, I'm still inside the equation editor - I can't "get out" of the equation back to normal text insertion. I tried to record a macro and manually enter a equation and then insert more normal text afterwards, but the macro record function doesn't seem to be able to handle the equation editor.
What I would like to do in pseudo code is this:
Selection.TypeText Text:="How to solve this equation?"
Selection.TypeEquation "1/2 + 1/3"
Selection.TypeText Text:="First you have to make the denominators equal by extending the fractions"
Selection.TypeEquation "1*3/2*3 + 1*2/3*2"
Selection.TypeText Text:="Now you can...."
Any ideas?

Developer technologies Visual Basic for Applications
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2022-10-26T11:16:35.92+00:00

    Check if this example works for you:

    Selection.TypeText "How to solve this equation?" & vbCrLf  
      
    Dim r As Range  
    Set r = Selection.Range  
    r.Text = "1/2 + 1/3"  
    Selection.Start = r.End + 1  
    Selection.End = Selection.Start  
    Selection.OMaths.Add(r).OMaths(1).BuildUp  
      
    Selection.TypeText vbCrLf & "First you have to make the denominators equal by extending the fractions"  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.