如何在下面的代码中使用数组来查找多个字符串?
Sub Replace18()
Dim rng As Range
Dim rws As Long
rws = Range("A" & Rows.Count).End(xlUp).Row - 3
Set rng = Rows("3:3").Find(What:="quantity", LookAt:=xlWhole, MatchCase:=False)
If Not rng Is Nothing Then
rng.Offset(1, 0).FormulaR1C1 = "20"
rng.Offset(1, 0).Resize(rws).FillDown
End If
End Sub
最佳答案
设置一个变量数组并循环遍历它们。
Sub Replace18()
Dim rng As Range, rws As Long, w As Long, vWHATs As Variant
vWHATs = Array("Lorem", "ipsum", "dolor", "amet", "consectetur", "adipiscing", _
"elit", "Mauris", "facilisis", "rutrum", "faucibus", "Sed", _
"euismod", "orci", "rhoncus", "tincidunt", "elit", "eros")
With Worksheets("Sheet2") '<~~set this worksheet reference properly!
rws = .Cells.SpecialCells(xlCellTypeLastCell).Row - 3
For w = LBound(vWHATs) To UBound(vWHATs)
Set rng = .Rows(3).Find(What:=vWHATs(w), LookAt:=xlWhole, MatchCase:=False)
If Not rng Is Nothing Then
'just fill then all at once
rng.Offset(1, 0).Resize(rws, 1) = "20"
End If
Next w
End With
End Sub
我已修改您对“最后一行”的搜索,以包含所有带有 Range.SpecialCells method 的列使用 xlCellTypeLastCell选项。这最适用于我已包含在 With ... End With 中的正确引用的父工作表。堵塞。此 block 中的所有单元格和范围引用都应带有句点(又名
.
或句号)作为前缀,以注意它们属于 With ... End With 中引用的工作表。这包括 .Rows(3)
就像 .Find
使用前缀句点表示它引用了 Rows(3)
.
关于excel - 使用数组并在 vba 中使用以下代码查找多个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34106818/