在一系列单元格中搜索特定字符串并替换

时间:2016-03-01 15:00:34

标签: excel vba macros

我想在一系列单元格中搜索某些字符串值,并用其他内容替换它们。目前我正试图检查从AS22到??

的一个列范围

我想要搜索的是:

Green
Amber
Red

并替换为:

On Track
Minor Variance
Major Variance

这是我到目前为止的代码,但它不起作用,我没有收到任何错误 - 不确定是什么错误。

Dim i As Variant
Dim k As Variant
    i = ("Green, Amber, Red")
    k = ("On Track, Minor Variance, Major Variance")
    Columns("AS").Replace What:=i, Replacement:=k, lookat:=xlPart, MatchCase:=False

理想情况下,我想立即搜索AS,AT,AU列,而不必复制代码三次。

任何人都可以了解这段代码不起作用的原因

3 个答案:

答案 0 :(得分:3)

考虑:

Sub qwerty()
        With Range("AS:AU")
            .Replace what:="Green", Replacement:="On Track"
            .Replace what:="Amber", Replacement:="Minor Variance"
            .Replace what:="Red", Replacement:="Major Variance"
        End With
End Sub

答案 1 :(得分:2)

将值作为数组分配到相应的变量变量中,然后使用LBound functionUBound function循环访问它们以定义范围。

Dim i As Variant, k As Variant, w As Long

i = Array("Green", "Amber", "Red")
k = Array("On Track", "Minor Variance", "Major Variance")

With Worksheets("Sheet1")    '<~~you should know what worksheet you are on~
    For w = LBound(i) To UBound(i)
        .Columns(45).Replace what:=i(w), replacement:=k(w), _
                       lookat:=xlWhole, MatchCase:=False
    Next w
End With

根据我上面的评论,我已将lookat:=xlPart替换为lookat:=xlWhole

答案 2 :(得分:0)

Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long

fndList = Array("Red", "Amber", "Green")
rplcList = Array("On track", "Minor Variance", "Minor Variance")

'Loop through each item in Array lists
  For x = LBound(fndList) To UBound(fndList)
    'Loop through each worksheet in ActiveWorkbook
      For Each sht In ActiveWorkbook.Worksheets
        sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
          LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
          SearchFormat:=False, ReplaceFormat:=False
      Next sht

  Next x