VBA Excel搜索包含不同单词之一的单元格

时间:2016-06-14 20:31:32

标签: arrays string excel vba search

我需要制作一个脚本来着色或删除至少包含我需要搜索的单词之一的行。例如,我有一个数组或只是一个单词列表,如“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

谢谢你们!

2 个答案:

答案 0 :(得分:1)

我首先会创建一个特殊单词数组

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

答案 1 :(得分:0)

试试这个

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