Search code examples
vbams-wordequations

VBA (word) Writing a equation in a table


So I am working on a word template which needs to automatically write specific data in specific places of the document. Now I Need to write and mathematical equation in a cell (for example: 〖∆U=α〗_(steel )∙ ∆T ∙ ∆L_vp) I know I need to replace certain characters with a ChrW(###). But I cant seem to figure out how to write the formula in the right format in the cell (specific location in the code below "my equation here". Note this is only one cell as an example but there are more cell that are filled under the with activedocument.tables. Can anybody here help me out?

'Selecteren Table
With ActiveDocument.Tables(TableNum)

    'Select cell to write data in
        With .cell(r, 1)
        'data to be written in cell    
        With .Range
                .Text = "My Equation here"
            End With
        End With

end with

Just to clarify the use of the with part of the code

'Select right table With ActiveDocument.Tables(TableNum)

    'add row when a Tee is already inserted
    If insertrow = True Then
        ActiveDocument.Tables(TableNum).cell(r, 1).Select
        Selection.InsertRows (1)
    End If

    'Select cell and write data
        With .cell(r, 1)
            With .Range
                'lettertype updaten voor betreffende cell
                With .Font
                .Bold = True
                End With
                .Text = TxtTstuk.Value & ":"
            End With
        End With

        'Select cell and write data
        With .cell(r, 2)
            With .Range
                .Text = "Type T-stuk:"
            End With
        End With

        'Select cell and write data
        With .cell(r, 3)
            With .Range
                .Text = TxtTType.Value
            End With
        End With

    'add 1 to counter
    r = r + 1

    'Add row
    If insertrow = True Then
        ActiveDocument.Tables(TableNum).cell(r, 1).Select
        Selection.InsertRows (1)
    Else
        ActiveDocument.Tables(TableNum).Rows.Add
    End If

    'Select cell and write data
        With .cell(r, 2)
            With .Range
                .Text = "Diameter doorgaande leiding:"
            End With
        End With

and so on...


Solution

  • Since you're only using a single property, what is the purpose of nested With?

    Modify it to suit your needs.

    Sub WriteEq()
    
        Dim objRange As Range
        Dim objEq As OMath
    
        With ActiveDocument
            Set objRange = .Tables(1).Cell(1, 1).Range
                objRange.Text = "Celsius = (5/9)(Fahrenheit – 32)"
            Set objRange = .OMaths.Add(objRange)
        End With
    
        Set objEq = objRange.OMaths(1)
            objEq.ConvertToMathText
            objEq.BuildUp
    
    End Sub