![](/img/trans.png)
[英]VBA Excel: How to check if a value is in a selected range of values (or current cell)
[英]Excel VBA check multiple values in a cell
我試圖做一個宏,檢查特定值的列。 我嘗試了一下。 它檢查特定值,但問題是它僅檢查單個值。
例如-假設有三個單元格。
Cell 1 contains Red
Cell 2 contains Black
Cell 3 contains Red;Black
運行宏后,將突出顯示單元格3。
雖然我已經在數組中添加了兩種顏色,但是它正在檢查是否完全匹配。
Cells.Find(What:="Color Filter", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
Dim myarray As Variant
Dim r As Variant
myarray = Array("Beige", "Black", "Blue", "Brown", "Cream", "Green", "Grey", "Maroon", "Multi", "Orange", "Pink", "Purple", "Red", "Rust", "Turquoise", "Violet", "White", "Wine", "Yellow", "Transparent")
Dim Rng As Range
Dim Dn As Range
Set Rng = Range(Cells(MyRow, MyCol), Cells(LastRow, MyCol))
For Each Dn In Rng
For Each r In myarray
If Dn = r Then
Dn.Interior.ColorIndex = xlNone
Exit For
ElseIf Dn = "" Then
Dn.Interior.ColorIndex = 3
Else
Dn.Interior.ColorIndex = 3
End If
Next r
Next Dn
您可以使用Instr
函數根據單元格中的Value評估數組的每個成員。 這將在單元格值中的任何位置查找每種顏色。
我略微重構了您的代碼,這樣(我認為)可以保持您的原始意圖。
Dim myarray As Variant, r As Variant
myarray = Array("Beige", "Black", "Blue", "Brown", "Cream", "Green", "Grey", "Maroon", "Multi", "Orange", "Pink", "Purple", "Red", "Rust", "Turquoise", "Violet", "White", "Wine", "Yellow", "Transparent")
Dim Rng As Range, Dn As Range
Set Rng = Range(Cells(MyRow, MyCol), Cells(LastRow, MyCol))
For Each Dn In Rng
If Dn = "" Then
Dn.Interior.ColorIndex = 3
Else
For Each r In myarray
If InStr(r, Dn.Value2) Then
Dn.Interior.ColorIndex = xlNone
Exit For
End If
Next r
End If
Next Dn
斯科特的解決方案看起來不錯。 另一個選擇是使用split
然后創建一個循環...這將以某種方式允許您實際使用每種顏色的信息。 因此,在單元格包含Red;Black
的情況下,它將對第一部分進行一次評估,對第二部分進行第二次評估。
嘗試這樣:
Dim myarray As Variant, r,cs,CutString As Variant
myarray = Array("Beige", "Black", "Blue", "Brown", "Cream", "Green", "Grey", "Maroon", "Multi", "Orange", "Pink", "Purple", "Red", "Rust", "Turquoise", "Violet", "White", "Wine", "Yellow", "Transparent")
Dim Rng As Range, Dn As Range
Set Rng = Range(Cells(MyRow, MyCol), Cells(LastRow, MyCol))
For Each Dn In Rng
If Dn = "" Then
Dn.Interior.ColorIndex = 3
Else
For Each r In myarray
CutString = Split(Dn.Value2, ";")
For Each cs In CutString
If cs = r Then
Dn.Interior.ColorIndex = xlNone
Exit For
End If
Next cs
Next r
End If
Next Dn
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.