vba 处理word 的一些代码:修改公式(1--1)为(1-1)

发布时间 2023-10-29 15:19:22作者: ChrainY

Sub ConvertSpecificEquationsToText()
Dim oEq As OMath
Dim eqText As String
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")

' Define the regular expression pattern
regEx.Pattern = "(\d.?\d)" ' Pattern for (digit?digit)
regEx.Global = True

' Loop through each equation in the document
Dim oMaths As oMaths
Set oMaths = ActiveDocument.oMaths

Dim i As Long
Dim p As Paragraph
Dim tabStop As tabStop
Dim tabsArray() As Double
Dim alignsArray() As WdTabAlignment
Dim leadersArray() As WdTabLeader
Dim j As Integer

For i = oMaths.Count To 1 Step -1
    Set oEq = oMaths(i)
    eqText = oEq.Range.Text
    Debug.Print "Equation Text: " & eqText
    
    ' Check if the equation text matches the pattern
    If regEx.Test(eqText) Then
        ' Store current paragraph's tab stops
        Set p = oEq.Range.Paragraphs(1)
        
        ReDim tabsArray(1 To p.TabStops.Count)
        ReDim alignsArray(1 To p.TabStops.Count)
        ReDim leadersArray(1 To p.TabStops.Count)
        
        For j = 1 To p.TabStops.Count
            Set tabStop = p.TabStops(j)
            tabsArray(j) = tabStop.Position
            alignsArray(j) = tabStop.Alignment
            leadersArray(j) = tabStop.Leader
        Next j
        
        ' Convert the equation to normal text
        oEq.Range.oMaths(1).ConvertToNormalText
        
        ' Apply the "Normal" style
        oEq.Range.Style = wdStyleNormal
        
        ' Restore the tab stops
        p.TabStops.ClearAll
        For j = 1 To UBound(tabsArray)
            p.TabStops.Add Position:=tabsArray(j), Alignment:=alignsArray(j), Leader:=leadersArray(j)
        Next j
        
        Debug.Print "Converted: " & oEq.Range.Text
    End If
Next i

End Sub