【问题标题】:VBA Excel Search for cell that contain one of different wordVBA Excel搜索包含不同单词之一的单元格
【发布时间】:2016-10-15 17:58:58
【问题描述】:

我需要编写一个脚本来着色或删除包含至少一个我需要搜索的单词的行。例如,我有一个数组或只是一个单词列表,如“alpha”“beta”“gamma”,我需要在列 A 和 B 中搜索有不同的单词和字符串,如果这些单词存在,至少一个它们,然后着色或删除该行,但这不是问题。这就是我所做的,在互联网上找到某个地方,但它不起作用。我有大约 30 个字要搜索,甚至更多。你能帮助我吗?

   Sub Macro2()
'
' Macro2 Macro
'


For i = 2 To 1000
If Evaluate("COUNT(SEARCH({""alpha"",""beta"",""gamma""}," & Cells(i, 1).Address & "))") > 0 Then
Rows(i).Interior.Color = RGB(127, 187, 199)
GoTo Prossimo
End If
If Evaluate("COUNT(SEARCH({""alpha"",""beta"",""gamma""}," & Cells(i, 2).Address & "))") > 0 Then
Rows(i).Interior.Color = RGB(127, 187, 199)
GoTo Prossimo
End If
Prossimo:
Next i
End Sub

谢谢你们!

【问题讨论】:

    标签: arrays string excel vba search


    【解决方案1】:

    试试这个

    Option Explicit
    
    Sub Macro2()
       Dim cell as Range
       Dim myWords as String
    
       myWords = "|alpha|beta|gamma|"
       With Worksheets("MySheet") '<--| change "MySheet" to your actual sheet name
          For Each cell in .Range("A2:A" & .Cells(.Rows.Count,"A").End(xlUp).Row)
             If InStr(myWords, "|" & cell.Value & "|") > 0 or InStr(myWords, "|" & cell.Offset(,1).Value & "|") > 0 Then cell.EntireRow.Interior.Color = RGB(127, 187, 199)
          Next cell   
       End With
    End Sub
    

    【讨论】:

    • 好像什么都没发生
    • 我没有通过任何电脑检查它
    • 我没有通过任何 PC 来检查它。因此,尝试单步执行代码并在即时窗口中查询“cell”、“cell.Address”、“InStr(myWords, “|” & cell.Value & “|”)”和“InStr(myWords,”的值|" & cell.Offset (,1).Value & "|")" 在每个循环。代码假设如下:1)相关工作表以“MySheet”命名 2)从第 2 行到 A 列的最后一个非空行检查 A 列和 B 列中的值。3)如果任一列中的单元格,则在每一行A 或 B 的内容为“alpha”或“beta”或“gamma”,那么整行都是彩色的
    • @BigBlack 现在我对其进行了测试并且它可以工作,并根据我之前的评论进行假设。你有什么问题?
    • 我试图在局部变量窗口中查看,但我不知道在哪里搜索以查看是否找到单词。
    【解决方案2】:

    我将首先创建一个包含您的特殊单词的数组

    words = Array("alpha", "beta", ...)
    

    然后您可以遍历电子表格中的行和数组中的项目,寻找匹配项。

    words = Array("alpha", "beta", ...)
    for i = 2 to 1000
        for j = lbound(words) to ubound(words)
            if cells(i,1)=words(j) or cells(i,2)=words(j) then
                rows(i).interior.color=rgb(127,187,199)
            end if
        next j
    next i
    

    【讨论】:

    • 有一些奇怪的东西,但它开始和结束时没有任何颜色......
    • 我测试它时效果很好。你的输入是什么样的?
    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2016-03-21
    相关资源
    最近更新 更多