Vba omath to word

I am creating a word report through excel VBA. I need math equation to be written but unfortunately, the word document do not autocorrect pi and times. Otherwise the equation is printed. Can someone suggest me what is the way forward. Below is the code

Sub AreaSolidBolt(wrdApp As Object, wrdDoc As Object, d As Variant)
Dim objRange As Object
Dim objEq As OMath
Dim aCorrect As OMathAutoCorrectEntry
wrdApp.OMathAutoCorrect.UseOutsideOMath = True

Set objRange = wrdDoc.Range
objRange.Text = "A = pi/4 times d^2"
Set objRange = wrdApp.Selection.OMaths.Add(objRange)
    For Each aCorrect In wrdApp.OMathAutoCorrect.Entries
        With objRange
            If InStr(.Text, aCorrect.Name) > 0 Then
                .Text = Replace(.Text, aCorrect.Name, aCorrect.Value)
            End If
        End With
    Next aCorrect
Set objEq = objRange.OMaths(1)
objEq.BuildUp

Set objRange = Nothing
End Sub

I have defined the objects as below in the calling function. Can you please suggest me the way forward.

Set fso = CreateObject("Scripting.FileSystemObject")
Set wrdApp = CreateObject("Word.Application")

If Not fso.FileExists(wrdFileName) Then
    Set wrdDoc = wrdApp.Documents.Add
    wrdApp.Visible = False
    With wrdDoc
        .SaveAs FileName:=wrdFileName
    End With
Else
    Set wrdDoc = wrdApp.Documents.Open(wrdFileName)
    wrdApp.Visible = False
    wrdDoc.Content.InsertAfter vbLf
End If

Cindy Meister's user avatar

asked Jan 14, 2018 at 1:09

Raghu's user avatar

If the AutoCorrect isn’t recognizing something you need to use, then you can write in the corresponding (unicode) character code as part of the equation, using ChrW(). PI is 960, for example.

It’s not clear what you consider a «times» character, whether an «x» an «*» or something else. I note that most Math equations don’t actually use a character for multiplication, which may be why AutoCorrect isn’t picking that up. But you can certainly just type those in?

For example:

 objRange.Text = "A = " & ChrW(960) & "/4 * d^2"

answered Jan 14, 2018 at 9:31

Cindy Meister's user avatar

Cindy MeisterCindy Meister

24.9k21 gold badges35 silver badges43 bronze badges

5

I have found the answer myself. The was slightly modified. The error was with the placement of the code line
Set objRange = wrdApp.Selection.OMaths.Add(objRange)

Below is the modified code.

Sub AreaSolidBolt(wrdApp As Object, wrdDoc As Object, d As Variant)
Dim objRange As Object
Dim objEq As OMath
Dim aCorrect As OMathAutoCorrectEntry
wrdApp.OMathAutoCorrect.UseOutsideOMath = True

Set objRange = wrdDoc.Range
objRange.Text = "A = pi/4 times d^2"
For Each aCorrect In wrdApp.OMathAutoCorrect.Entries
   With objRange
      If InStr(.Text, aCorrect.Name) > 0 Then
          .Text = Replace(.Text, aCorrect.Name, aCorrect.Value)
       End If
   End With
Next aCorrect
Set objRange = wrdApp.Selection.OMaths.Add(objRange)
Set objEq = objRange.OMaths(1)
objEq.BuildUp

Set objRange = Nothing
End Sub

answered Apr 7, 2018 at 7:56

Raghu's user avatar

RaghuRaghu

1141 silver badge9 bronze badges

1

Permalink

main

Switch branches/tags

Could not load branches
Nothing to show

{{ refName }}
default

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Go to file

  • Go to file

  • Copy path


  • Copy permalink

Cannot retrieve contributors at this time

OMath object (Word)
Remarks
Methods
Properties
See also

79 lines (57 sloc)

1.93 KB


Raw


Blame

Open in GitHub Desktop

  • Open with Desktop

  • View raw


  • Copy raw contents

  • View blame

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

OMath object (Word)

vbawd10.chm2691

vbawd10.chm2691

word

Word.OMath

82f2f81b-e2d5-140f-bdcc-8b52b821b24d

06/08/2017

medium

OMath object (Word)

Represents an equation. OMath objects are members of the OMaths collection.

Remarks

Use the Add method of the OMaths collection to create an equation and add it to a document, selection, or range. The following example creates an equation and uses the BuildUp method to convert the equation to professional format.

Dim objRange As Range 
Dim objEq As OMath 
 
Set objRange = Selection.Range 
objRange.Text = "Celsius = (5/9)(Fahrenheit - 32)" 
Set objRange = Selection.OMaths.Add(objRange) 
Set objEq = objRange.OMaths(1) 
objEq.BuildUp

Methods

Name
BuildUp
ConvertToLiteralText
ConvertToMathText
ConvertToNormalText
Linearize
Remove

Properties

Name
AlignPoint
Application
ArgIndex
ArgSize
Breaks
Creator
Functions
Justification
NestingLevel
Parent
ParentArg
ParentCol
ParentFunction
ParentOMath
ParentRow
Range
Type

See also

Word Object Model Reference

[!includeSupport and feedback]

In this article I will explain how you can create equations using VBA for word.


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:

Word Equation
If you copy the equation and paste it in a notepad this is what you get:

Word Equation in NotePad
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:

Word, Equation Linear
Step 2: Select the text in the word document and click on the “Insert Equation” button on the “Insert” tab

Word Equation, Insert
Step 3: Choose professional View:

Word Equation Professional View
Result:

Word, Equation Professional
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.


Step 2:

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:

  • Word VBA Using Bookmarks to Move the Cursor
  • Word VBA, Move Cursor to Start of Document
  • Word VBA, Move Cursor to End of Document
  • Word VBA, Move Cursor to End of Line
  • Word VBA, Move Cursor to Start of Line
  • Word VBA, Go to Specific Line


Creating Simple Equations :

Equations can be made using the code below:

Sub Example1()
Dim objRange As Range
Set objRange = Selection.Range
objRange.Text = "y = x^2+1"
Call OMaths.Add(objRange)
End Sub

Word VBA Insert Equation Restul
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

Create equation


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 :

  • “y = x^2+1”

with

  • “f(x)=a_0+∑_(n=1)^∞▒(a_n  cos⁡〖nπx/L〗+b_n  sin⁡〖nπx/L〗 ) “

But this is what will happen if we try to make this replacement:

Sub Example1()
Dim objRange As Range
Set objRange = Selection.Range
objRange.Text = _
"f(x)=a_0+?_(n=1)^8n(a_n  cos??npx/L?+b_n  sin??npx/L? ) "
Call OMaths.Add(objRange)
End Sub

As you can see a lot of the characters are not recognized by the VBA editor and are replaced by a “?” character. The solution to this is explained in the steps below:

Step 1: Break the text string into different segments, separating the “?” characters:

"f(x)=a_0+" + ? + "_(n=1)^8n(a_n  cos"+ ?? + _
"npx/L" + ?+ "+b_n  sin' + ?? + "npx/L" +? +" ) "

For more information about concatenating strings please see the link below:

  • VBA Excel String Processing and Manipulation

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:

  • VBA Get Characters Unicode Value

Step 3: Replace the “?” characters with the ChrW() function. The ChrW() function receives as input a unicode value and returns the character associated with it:

Sub Example3()
Dim objRange As Range
Dim objOMath As OMath
Set objRange = Selection.Range
objRange.Text = _
"f(x)=a_0+" + ChrW(8721) + "_(n=1)^8" + ChrW(9618) + _
"(a_n  cos" + ChrW(12310) + "npx/L" + ChrW(12311) + _
"+b_n  sin" + ChrW(12310) + "npx/L" + ChrW(12311) + " )"
Set objOMath = OMaths.Add(objRange).OMaths.Item(1)
objOMath.BuildUp
End Sub

Result:

Word Equaton Complex
You can download the file and code related to this article from the link below:

  • Create Word Equation.docm

See also:

  • Word VBA Equations Linear/Professional Display
  • Microsoft (MSDN) OMath Object (Word)

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

score:0

Accepted answer

I have found the answer myself. The was slightly modified. The error was with the placement of the code line
Set objRange = wrdApp.Selection.OMaths.Add(objRange)

Below is the modified code.

Sub AreaSolidBolt(wrdApp As Object, wrdDoc As Object, d As Variant)
Dim objRange As Object
Dim objEq As OMath
Dim aCorrect As OMathAutoCorrectEntry
wrdApp.OMathAutoCorrect.UseOutsideOMath = True

Set objRange = wrdDoc.Range
objRange.Text = "A = pi/4 times d^2"
For Each aCorrect In wrdApp.OMathAutoCorrect.Entries
   With objRange
      If InStr(.Text, aCorrect.Name) > 0 Then
          .Text = Replace(.Text, aCorrect.Name, aCorrect.Value)
       End If
   End With
Next aCorrect
Set objRange = wrdApp.Selection.OMaths.Add(objRange)
Set objEq = objRange.OMaths(1)
objEq.BuildUp

Set objRange = Nothing
End Sub

score:1

If the AutoCorrect isn’t recognizing something you need to use, then you can write in the corresponding (unicode) character code as part of the equation, using ChrW(). PI is 960, for example.

It’s not clear what you consider a «times» character, whether an «x» an «*» or something else. I note that most Math equations don’t actually use a character for multiplication, which may be why AutoCorrect isn’t picking that up. But you can certainly just type those in?

For example:

 objRange.Text = "A = " & ChrW(960) & "/4 * d^2"

Related Query

  • oMath from excel to word
  • Generate Word Documents (in Excel VBA) from a series of Document Templates
  • Reduce file size for charts pasted from excel into word
  • User defined type not defined- controlling Word from Excel
  • Extract Data from Word Document to an Excel SpreadSheet
  • Auto creating tables in Word from an Excel document
  • pasting from excel into a word document
  • How do I change text in a Word Doc from Excel VBA when Word Doc is located on a server?
  • How can I copy one section of text from Word to Excel using an Excel macro?
  • How do I keep Excel from binding to the Microsoft Word 15.0 Object Library?
  • Update linked fields in Word document from Excel VBA
  • How to save/copy an embedded picture from Excel to Word
  • Open word from excel
  • copy-paste tables from word to excel
  • Activate Word window from Excel with VBA
  • Select a VBA Pasted Shape from Excel to Word so I can wrap text tight
  • Removing the Contents from the Cell of a Word Table using Excel VBA
  • Can’t use ‘Selection.TypeText’ method when writing to Word document from Excel VBA
  • Creating and saving Excel document From VBA in Word
  • How do I generate a formatted Word report from multi-row/column Excel spreadsheet
  • Generate word documents from excel file using mail merge
  • Closing word application from excel vba
  • Calling a Word VBA Sub with arguments from Excel VBA
  • VBA — Why opening Word from Excel is slow?
  • Using the Word Selection object from an excel macro
  • Filter for a word from a string in excel
  • Open Word document from Excel (Office 2016 and MacOS)
  • HOW To manipulate an ALREADY open word document from excel vba
  • Inserting Header/Footer into newly created word document from Excel VBA
  • VBA Excel Copy Content From Word Table

More Query from same tag

  • Can the list for an Excel dropdown menu be contained in a single cell?
  • How to stay on the UserFrom during the excution of the vba
  • Excel VBA Assignment by value or by reference?
  • Read string from text file in url using VBA
  • How can I calculate an entire workbook, but not all open workbooks?
  • Excel VBA — Change cell colour based on event from other sheets
  • Highlight strings in a cell in Excel based on a string in adjacent cell
  • Sort Worksheet that’s not Active/Visible
  • How to copy data from one workbook to another?
  • Find Last Column used in excel sheet using VBA in Microsoft Word
  • Allow listbox to display no results when ListBox.RowSource returns no results
  • error parsing HTML with excel vba
  • Using VBA in excel to send instant message
  • Hide rows based on Date input
  • how to set image Aspect ratio to 100 % in Powerpoint 2007 using vba?
  • Stripping HTML From A String
  • VBA Delete row if
  • Separating copied cells
  • How to copy a row depending on a value in a cell
  • Manipulating excel «autoshapes» with VBA
  • Userform visibility
  • VBA Macro to combine two sheets based on common ID number number using Match Function or VLookUp
  • Automatically add rows into a MS Word table in a loop as long as you read data from the excel sheet
  • Creating a Calendar in Access 2010
  • VBA Images lost when inserting one word document into another
  • how to copy specific cells of data (skipping blank cells) into another worksheet into next blank row?
  • Format Word 2016 table cell
  • Change olMail.Body font name and font size if olMail.Body = str1 + str2
  • Find matching last row and check if the next column row is empty
  • Kofax Transformation VBA Script to update field value

  • #2

It seems that BuildUp doesn’t AutoCorrect:

Code:

Sub genEQ()
    Dim objRange As Range
    Dim objEq As OMath
    Dim AC As OMathAutoCorrectEntry
    Application.OMathAutoCorrect.UseOutsideOMath = True
    Set objRange = Selection.Range
    objRange.Text = "Celsius = sqrt(x+y) + sin(5/9 times(Fahrenheit – 23 (delta)^2))"
    For Each AC In Application.OMathAutoCorrect.Entries
        With objRange
            If InStr(.Text, AC.Name) > 0 Then
                .Text = Replace(.Text, AC.Name, AC.Value)
            End If
        End With
    Next AC
    Set objRange = Selection.OMaths.Add(objRange)
    Set objEq = objRange.OMaths(1)
    objEq.BuildUp
End Sub

Понравилась статья? Поделить с друзьями:
  • Vba for excel оператор if логические операторы
  • Vba numbered list in word
  • Vba for filter in excel
  • Vba for excel округление чисел
  • Vba number of rows in excel