excel - 使用数组并在 vba 中使用以下代码查找多个字符串?

标签 excel vba

如何在下面的代码中使用数组来查找多个字符串?

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/

相关文章:

excel - 使用 Office Open Xml SDK 以编程方式格式化 Excel 工作表中的日期

c# - 是否有 Excel 图表对象到 System.Windows.Forms.DataVisualization.Charting 转换器?

Excel VBA 代码完成(方法|属性)

尝试获取 InnerText 时需要 VBA 对象错误

vba - 当行数变化时使用worksheet_calculate

arrays - 数组中的 VBA SumIf

javascript - 有什么办法可以在从js生成的excel文件上设置安全内容吗?

vba - 如何从工作表中删除公式但保留其计算值

python - 如何根据值更改Excel单元格颜色?

sql - VBA 多 SQL 查询到 Excel