搜索阵列VBA Excel

时间:2014-01-03 13:27:49

标签: excel vba excel-vba

我希望vba在给定的单元格中搜索这些短语中的“ANY”,如果它应该发现这些短语中的任何一个改变了另一个单元格中的文本颜色,则其他明智地将其变为红色。 到目前为止,我可以让它搜索单元格,但它标记为红色,即使我知道它们应该是绿色的。我假设它没有搜索数组的整个内容。 以下是我到目前为止的情况:

Sub Test()

    Dim celltxt1 As String, mvarr1, a

    celltxt = ActiveSheet.Range("G21:G128").Select
    mvarr1 = Array("Tom", "Alison1", "Paul", "Deb2", "Pr123", "21", "18", "Pie-1", "Run", "Swim")


   For Each a In mvarr1
       If (InStr(1, celltxt1, CStr(a), vbTextCompare) > 0) Then              
            ActiveSheet.Range("I21:I128").Font.Color = vbGreen
      Else
            ActiveSheet.Range("I21:I128").Font.Color = vbRed
      End If
   Next a
End Sub

任何建议或建议都将不胜感激

3 个答案:

答案 0 :(得分:0)

尝试使用此代码:

Sub Test()

   Dim celltxt1 As String, mvarr1, a

   celltxt = ActiveSheet.Range("G21:G128").Select
   mvarr1 = Array("Tom", "Alison1", "Paul", "Deb2", "Pr123", "21", "18", "Pie-1", "Run", "Swim")

   Dim isFound As Boolean
   isFound = False

   For Each a In mvarr1
     If (InStr(1, celltxt1, CStr(a), vbTextCompare) > 0) Then
          isFound = True
          Exit For
     End If
   Next a

   If isFound = True Then
       ActiveSheet.Range("I21:I128").Font.Color = vbGreen
   Else
       ActiveSheet.Range("I21:I128").Font.Color = vbRed
   End If

End Sub

答案 1 :(得分:0)

因为您为数组中的每个项目设置颜色,如果找不到数组中的最后一项,无论之前发生了什么,它都会变为红色。

最简单的更改只是将默认设置为红色,然后设置为绿色(如果找到)。 您也可以使用Exit For在找到第一个匹配项后停止循环。

Dim clrCell
clrCell = vbRed

For Each a In mvarr1
   If (InStr(1, celltxt1, CStr(a), vbTextCompare) > 0) Then              
       clrCell = vbGreen  
       Exit For
   End If
Next a

ActiveSheet.Range("I21:I128").Font.Color = clrCell 

答案 2 :(得分:0)

如果您只是想让“I”列中的每个相应单元格成为基于“G”列中单元格的颜色,那么您将需要使用OFFSET函数。

Sub Test()
    Dim celltxt1 As String, mvarr1, a
    Set celltxt = ActiveSheet.Range("G21:G128")
    mvarr1 = Array("Tom", "Alison1", "Paul", "Deb2", "Pr123", "21", "18", "Pie-1", "Run", "Swim")
    For Each b In celltxt
       b.Select
           For Each a In mvarr1
               If (InStr(1, b, CStr(a), vbTextCompare) > 0) Then
                   ActiveCell.Offset(0, 2).Font.Color = vbGreen
                   Exit For
               Else
                   ActiveCell.Offset(0, 2).Font.Color = vbRed
               End If
           Next a
    Next b
End Sub