查找并替换字符串VBA中的多个字符

时间:2014-02-17 10:10:21

标签: vba excel-vba replace excel-2010 excel

我想要在宏的帮助下替换大量数据。我现在正在使用下面的代码,但问题是它只会替换下面代码中的一个D值。

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 

我的示例数据如下。正如您所看到的那样,某些值在结尾处具有字母字符,符号或字符组合,或者作为单元格值,我想要替换或删除,并且某些值将替换为其他值。我创建了宏,可以找到所需的值并替换它。

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

您还注意到还有一些小写字符。现在我正试图在查找中使用 IF 条件,但无法成功。我正在使用宏的每个可能的条件来替换并从另一个宏运行它,这就像下面的算法。

IF  find "D"  Then

Run macro "Replace"

Elseif  find "X"

Run macro "Replace"

Elseif  find "F"

Run macro "Replace"

and so on....

但是如果宏没有在工作表中找到所需的字符,那么它将跳到下一步,依此类推。我想要这么糟糕。我必须多次执行此替换例程。

所以任何帮助将不胜感激。

由于

1 个答案:

答案 0 :(得分:2)

您可以在toRemove()数组中添加/删除必要的字符。

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