Excel VBA中的条件搜索和替换

时间:2014-01-06 22:09:22

标签: excel search excel-vba replace conditional vba

我正在努力编写VBA代码,该代码将搜索单元格中的文本字符串并删除部分文本,例如“John Smith QC”,只留下“John Smith”,然后将删除的文本“QC”放入相邻的单元格中。

我正在努力的部分是我无法让代码继续重复,直到它不再找到文本然后继续搜索新文本,例如“OAM”

我正在尝试的代码是:

postnom = " QC"
postnomnew = "QC"

Cells.Find(What:=postnom, After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
    , SearchFormat:=False).Activate
ActiveCell.Replace What:=postnomnew, Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = postnomnew

Cells.FindNext(After:=ActiveCell).Activate

如果\ endif条件语句有效,我似乎无法得到,并且我不确定是否\ endif是最好的方法。

由于 罗恩

1 个答案:

答案 0 :(得分:0)

完全未经测试但你应该明白这一点。

Public Sub test()
    Dim rngTmp As Range
    Dim rngSearch As Range
    Dim postnom As String
    Dim postnomnew As String

    Dim wksTmp As Worksheet

    postnom = " QC"
    postnomnew = "QC"
    Set wksTmp = ActiveSheet

    Set rngSearch = wksTmp.Cells

    With rngSearch
      Set rngTmp = .Find(postnom, LookIn:=xlValues)
      If Not rngTmp Is Nothing Then

        Do
          wksTmp.Cells(rngTmp.Row, rngTmp.Column + 1).Value = postnomnew
          rngTmp.Value = Replace(rngTmp.Value, LCase(postnom), "")
          Set rngTmp = .FindNext(rngTmp)
        Loop While Not rngTmp Is Nothing

      End If

    End With
End Sub
编辑:我现在已经测试了,你可以摆脱使用findnext循环的测试,因为你删除了postnom,它们将不再被发现。关于REPLACE方法的注意事项,因为它不会捕获大小写更改(即QC!= qc)。