Skip to content

Instantly share code, notes, and snippets.

@gaspardpetit
Last active June 22, 2024 21:00
Show Gist options
  • Select an option

  • Save gaspardpetit/32b52907ead5172805465e5e9d70b8d5 to your computer and use it in GitHub Desktop.

Select an option

Save gaspardpetit/32b52907ead5172805465e5e9d70b8d5 to your computer and use it in GitHub Desktop.
VB Macro to Convert LaTeX to Word Equations
Sub ConvertLatexToWord()
Dim selectedRange As Range
Dim startPos As Long
Dim endPos As Long
Dim equationText As String
Dim insertRange As Range
Dim undoRecord As undoRecord
Dim equations As Collection
Dim eqRange As Range
' Check if there is a valid text selection
If Selection.Type <> wdSelectionNormal Then
MsgBox "Please select the text containing LaTeX equations to convert.", vbExclamation
Exit Sub
End If
' Start an undo record
Set undoRecord = Application.undoRecord
undoRecord.StartCustomRecord "Convert LaTeX Equations"
' Set the range to the current selection
Set selectedRange = Selection.Range
' Initialize the collection to store equation ranges
Set equations = New Collection
' Loop through the text to find LaTeX equations enclosed by $
Do While InStr(selectedRange.Text, "$") > 0
startPos = InStr(selectedRange.Text, "$")
If startPos = 0 Then Exit Do ' No opening $ found, exit loop
endPos = InStr(startPos + 1, selectedRange.Text, "$")
If endPos = 0 Then Exit Do ' No closing $ found, exit loop
' Extract the equation text
equationText = Mid(selectedRange.Text, startPos + 1, endPos - startPos - 1)
' Create a range for the equation
Set insertRange = selectedRange.Duplicate
insertRange.Start = selectedRange.Start + startPos - 1
insertRange.End = selectedRange.Start + endPos
' Insert the equation text
insertRange.Text = equationText
' Add OMath object
insertRange.OMaths.Add insertRange
' Add the range to the collection
equations.Add insertRange.Duplicate
' Update the selectedRange to reflect changes
selectedRange.Start = insertRange.End + 1
Loop
' Process all collected equations with BuildUp
For Each eqRange In equations
eqRange.OMaths(1).BuildUp
Next eqRange
' End the undo record
undoRecord.EndCustomRecord
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment