I have some code in a particular coding language, and I am trying to clean it up by adding spaces around the variables. I wrote this code, and it works on small amounts of text and if I set a break point and run through it manually for large amounts of text. But when I try to run through it without frequently stopping the macro, Word stops responding and I have to restart the program. I think it is because the code is inefficient, but I don't have enough knowledge of vba to make it more efficient.
My code
Sub SpaceVarsAndEqns()
Dim i As Long
Dim paragraphIndex As Long
Dim characterIndex As Long
Dim isVar As Boolean
Dim varIndexBegin As Long
Dim varIndexEnd As Long
Dim Doc As Range
Dim Par As Range
Dim Char As Range
Set Doc = ActiveDocument.Range
For paragraphIndex = 1 To Doc.Paragraphs.Count
Set Par = Doc.Paragraphs(paragraphIndex).Range
isVar = False
characterIndex = 1
Do
Set Char = Par.Characters(characterIndex)
If isVar Then
If Char.Text = "$" Then
varIndexEnd = characterIndex
If Not Par.Characters(varIndexEnd + 1).Text = " " Then
Par.Characters(varIndexEnd).InsertAfter (" ")
characterIndex = characterIndex + 1
End If
If Not Par.Characters(varIndexBegin - 1).Text = " " Then
Par.Characters(varIndexBegin).InsertBefore (" ")
characterIndex = characterIndex + 1
End If
varIndexBegin = 0
varIndexEnd = 0
isVar = False
ElseIf Not (IsAlphaNumber(Char.Text) Or (Char.Text = ".")) Then
varIndexBegin = 0
varIndexEnd = 0
isVar = False
End If
Else
If Par.Characters(characterIndex).Text = "$" Then
varIndexBegin = characterIndex
isVar = True
End If
End If
characterIndex = characterIndex + 1
Loop While (characterIndex <= Par.Characters.Count)
Next paragraphIndex
End Sub
Text Before
\begin{bmatrix} $eval(($d$*$d.pmv$)/(|$d.et$|)*($d.et$*$xm$) + (($b$*-1)*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$) + $dist5$,0.###)\\ $eval((((($a$*$d$)-$d.et$)/($b$))*$d.pmv$*-1)/(|$d.et$|)*($d.et$*$xm$) + ($a$*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$)+ $dist6$,0.###) \end{bmatrix}
Text After
\begin{bmatrix} $eval(( $d$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $xm$ ) + (( $b$ *-1)* $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ ) + $dist5$ ,0.###)\\ $eval((((( $a$ * $d$ )- $d.et$ )/( $b$ ))* $d.pmv$ *-1)/(| $d.et$ |)*( $d.et$ * $xm$ ) + ( $a$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ )+ $dist6$ ,0.###) \end{bmatrix}
I think it could be improved by using a find method to find two consecutive $ symbols, and checking if the characters in between are consistent with a variable. However, I don't know how I would add spaces doing it this way.