Share via

Keeping leading zero when using Find and Replace in a macro

Anonymous
2017-12-13T21:02:27+00:00

Hello,

I have data in a column as listed below;

002 (xxxx......

2.0.03 (xxx.....

I am using the following to remove all data one character to the left of the parentheses and all data to the right.

Range("F1").Select

    Range(Selection, Selection.End(xlDown)).Select

    Selection.Replace What:=" (*", Replacement:="", LookAt:=xlPart, _

        SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _

        ReplaceFormat:=False

How ever I loose the leading zeros in 002 and would prefer to keep them.  Any suggestion on what I can do?

Thanks in advance.

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2017-12-13T22:01:46+00:00

This will force the values to be treated as strings:

Sub TestMacro1()

    Dim r As Range

    Dim c As Range

    Set r = Range(Range("F1"), Range("F1").End(xlDown))

    r.NumberFormat = "@"

    For Each c In r

        c.Value = "'" & c.Text

    Next c

    r.Replace What:=" (*", Replacement:="", LookAt:=xlPart, _

    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _

    ReplaceFormat:=False

End Sub

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2017-12-13T23:46:17+00:00

    This worked great, thanks

    Was this answer helpful?

    0 comments No comments