search数组VBA Excel

我希望vba在给定的单元格中search这些短语的“任意”,并且如果它发现这些短语中的任何一个都会改变另一个单元格中的文本的颜色。 到目前为止,我可以得到它来search单元格,但它标志着一切都是红色的,即使我知道他们应该是绿色的。 我假设它没有search数组的全部内容。 这是我迄今为止:

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 

任何意见或build议,将不胜感激

尝试使用此代码:

 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 

因为您为数组中的每个项目设置颜色,所以如果数组中的最后一个项目没有find,那么无论以前发生了什么,它都会变成红色。

最简单的改变就是设置为默认的红色,然后设置为绿色,如果有的话。 一旦find第一个匹配项,您也可以使用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 

如果你只是想让列“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