简体   繁体   中英

Find and replace multiple character in a string VBA

I have a large amount of data which i want to replace with the help of macro. I am using code below right now but problem is that it will only replace one value which is D in below code.

Sub Replace()

what = "D"
replc = ""

Sheets("Sheet1").Select

Cells.replace What:=word, Replacement:=replc, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=False

End Sub 

My sample data is below. As you can see that some value have alphabetical characters, symbol or combination of character at the end or as a cell value, which i want to replace or remove and also some value will be replaced with other values. I create macro with all possibilities to find the required value and replace it.

0065D 2089 2797 3270 3315 0066D 2095 2799 3300 3334 0067D 2105 2802 3582aX a 2089 – 2812 3307 3383 2095 2111 1164D 3315 3385 2105 2112 1165D 3334 3400 2110 2114 2841 3336F 3507 0771N 2121 2881 3365 3515N * 0908P * 2130 2883 3372X 3548 0913P 2131 2913 3373 3559 2111 2143 2915 3373 3574

You also notice that there are some lower case characters as well. Right now i was trying to use IF condition with Find but could not succeed. I am making above macro with every possible condition to replace and run it from another macro which is something like below algo.

IF  find "D"  Then

Run macro "Replace"

Elseif  find "X"

Run macro "Replace"

Elseif  find "F"

Run macro "Replace"

and so on....

but if the macro didn't find required character in the sheet then it skips to next step and so on. I want this so bad. I have to perform this replace routine on number of times.

So any help will be appreciated.

Thanks

You can add/remove necessary characters from the toRemove() array.

Sub replaceChars()
Dim toRemove()

toRemove() = Array("D", "X", "F")

For Each itm In toRemove()
    For Each iCell In ActiveSheet.UsedRange
        iCell.Replace What:=itm, Replacement:="", MatchCase:=True
    Next iCell
Next itm

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM