Search code examples
vbams-worddigits

How To Move Minus Sign From Right To Left?


I need an MSWord macro to convert these below values :

568.63- 682.3- 12.78-

To

-568.63 -682.3 -12.78


Solution

  • You don't actually need a macro for this. All you need is a wildcard Find/Replace with:

    Find = (<[0-9.]@)(-)
    Replace = \2\1
    

    As a macro, this would become:

    Sub Demo()
    Application.ScreenUpdating = False
    With ActiveDocument.Range
      With .Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "(<[0-9.]@)(-)"
        .Replacement.Text = "\2\1"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchWildcards = True
        .Execute Replace:=wdReplaceAll
      End With
    End With
    Application.ScreenUpdating = True
    End Sub
    

    As for the 80.9-100.1 issue identified by @Freeflow, I'd be inclined to replace those hyphens with something other than a normal hyphen (e.g. a non-breaking hyphen). In that case, you might use a macro coded like:

    Sub Demo()
    Application.ScreenUpdating = False
    With ActiveDocument.Range
      With .Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchWildcards = True
        .Text = "([0-9])-([0-9])"
        .Replacement.Text = "\1^~\2"
        .Execute Replace:=wdReplaceAll
        .Text = "(<[0-9.]@)(-)"
        .Replacement.Text = "\2\1"
        .Execute Replace:=wdReplaceAll
      End With
    End With
    Application.ScreenUpdating = True
    End Sub