View Single Post
 
Old 10-29-2021, 04:58 PM
davidjm davidjm is offline Windows 10 Office 2016
Novice
 
Join Date: Jun 2018
Posts: 18
davidjm is on a distinguished road
Default

Here's the code:

Code:
Sub perLine()
' Loops thru lines in document passing each line to following Sub ModifyNumbersInText(line)
Static objRegex As Object
Static matches As Object
    If objRegex Is Nothing Then Set objRegex = CreateObject("VBScript.RegExp")
Dim strSample As String

 Dim para As Paragraph
    Dim sentence() As String
    For Each para In ActiveDocument.Paragraphs
          sentence() = Split(para.Range.Text, Chr(11))
            For i = 0 To UBound(sentence)
                  strSample = sentence(i)                  
                      With objRegex
                       .Pattern = "(\-)(\d)"
                       .Global = True
                       .IgnoreCase = True
                       strSample = .Replace(strSample, " X $2")
                      End With
                  ModifyNumbersInText (strSample)
            Next i
    Next
End Sub

Sub ModifyNumbersInText(line)
'Adds 2 to all numerical values in line

Dim txt As String
Dim NumbersFound As String
Dim NumberArray As Variant
txt = line

'Use Regular Expressions to pull out numbers
  Set objRegex = CreateObject("VBScript.RegExp")
  objRegex.IgnoreCase = True
  objRegex.Global = True
  
  objRegex.Pattern = "\d+" 'grab one or more digits
  
  If objRegex.Test(txt) Then
    Set Result = objRegex.Execute(txt)
      If Result.Count > 0 Then
        For Each match In Result
          NumbersFound = NumbersFound & ";" & match.Value
        Next match
    Else
        Exit Sub
      End If
  End If

'Create Array out of Numbers Found
  NumbersFound = Right(NumbersFound, Len(NumbersFound) - 1)
  NumberArray = Split(NumbersFound, ";")
  
'Find/Replace (add 2)
  For x = LBound(NumberArray) To UBound(NumberArray)
    If NumberArray(x) > 30 Then
        txt = Replace(txt, NumberArray(x), NumberArray(x) + 2)
    End If
  Next x

'Output result
    Debug.Print txt
End Sub
This code is mostly tagged together from googling, but it all works apart from numbers pre-pended with "-". When I run
Code:
                  strSample = sentence(i)                  
                      With objRegex
                       .Pattern = "(\-)(\d)"
                       .Global = True
                       .IgnoreCase = True
                       strSample = .Replace(strSample, " X $2")
                      End With
on individual lines it replaces "-" followed by digit with " X " followed by digit.
Running Sub perLine() doesn't do the Regex replace above.

Snippet from Word document that I'm trying to update:

adaptive-expectations hypothesis 261–2, 305
aggregate demand 232–3, 305
aggregate supply 234–7, 305
aggregate supply curve 231
perfectly elastic 235
perfectly inelastic 235–6
aggregates levy 169

Thanks for any help
Reply With Quote