条件取决于是否发生替换

时间:2014-06-10 18:35:41

标签: excel vba replace

我想知道是否发生了替换。我希望能做什么:

bool SomethingWasReplaced = ActiveWorkbook.Worksheets(i).Cells.Replace What:="foo", Replacement:="bar", _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

If SomethingWasReplaced Then
...

我的互联网搜索没有显示出这样做的方法。我怎样才能实现我的目标?

1 个答案:

答案 0 :(得分:1)

我不认为有一种方法可以只用替换(尽管它说here),你可能不得不用搜索然后替换

Sub Test()

    Dim ws      As Worksheet
    Dim search  As Range
    Dim found   As Range

    For Each ws In ThisWorkbook.Sheets
        Set search = ws.Cells
        Set found = search.Find(What:="foo", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False)

        Do While Not found Is Nothing
            found.replace What:="foo", replacement:="bar"
            '' you now know something was replaced here, do whatever else you need   

            Set found = search.Find(What:="foo", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, After:=found)
        Loop
    Next ws

End Sub

我的怀疑是.Replace()如果有效(没有错误)则返回true,而不是基于它是否实际替换了任何内容。