如何在Excel中使用VBA进行search和replace?

我是VBA Excel编程的新手。 考虑一个具有nxn值的Excel工作表。 我的任务是从A列中search名为“TOOTHBRUSH BATT”的文本。 一列包含多个“TOOTHBRUSH”值。

一旦find值在单元格A11中,那么我需要将D11中的文本(即对应的D列)更改为“BATTERY”。 D11已经有一些文字了,我需要用“BATTERY”

我的代码是

Sub replacement() Dim S As String Dim H As String S = "TOOTHBRUSH BATT" For i = 1 To Range("A1").End(xlDown).Row If Range("A" & i) = S Then Range("D" & i) = "BATTERY" End If Next i End Sub 

 nRow = Worksheets(1).Range("A:A").Find(What:="*TOOTHBRUSH BATT*", after:=Range("A1"), LookIn:=xlFormulas, LookAt _ :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Row Worksheets(1).Cells(nRow,"D") = "BATTERY" 

通过使用自动filter(下面的代码未经testing)

 Worksheets(1).autofiltermode = false Worksheets(1).Range("A:B").autofilter Worksheets(1).AutoFilter.Range.AutoFilter Field:=1, Criteria1:="*TOOTHBRUSH BATT*" dim nRng as range If Worksheets(1).AutoFilter.Range.Offset(1,0).Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 Then set nRng = Worksheets(1).AutoFilter.Range.Offset(1,0).Columns(2).Resize(Worksheets(1).AutoFilter.Range.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible) nRng.value = "BATTERY" End If 

这与Eric的答案类似。

 ' Declare range to set to the first cell we find Dim find as Range set find = Range("A:A").Cells.Find(What:="TOOTHBRUSH BATT") ' This is the cell Address (in case it keeps looping back to beginning) Dim addy as string if not find is nothing then addy = find.address ' If we've found a cell then Keep Do something with it Do while not find is nothing find.Value = "BATTERY" ' Find the next Cell set find = Range("A:A").Cells.Find(What:="TOOTHBRUSH BATT", After:= find) ' If the next found cell is the first one then exit sub/function if find.address = addy then exit sub Loop