vba - conditional highlighting based on values
问题描述
I have defined a range which is filled with color based on the keywords in the cells. The aim is the highlighting of keywords as seen in figure below. One sees that the word "Auto" is searched and the cell is marked red. Where I get stuck is to extent the "if" command such as the search criteria carries onto the column E looks after the keywords "Mortgage", "Preferred" and "non-Preferred" and marks it in some colors. These keywords are always located in row "E" and in the first four columns next to the keyword "Auto". The trouble is that the three keywords "Mortgage", "Preferred" and "non-Preferred" do not always appear in the same order. It is possible that the keyword "preferred" might appear before "Mortgage".
Thus, my main question is whether there is a command in VBA so that the highlighting of these Keywords is done in a dynamic way without using a static colomn number as the order of these keywords can change.
Sub Schaltfläche2_Klicken()
Dim cell As Range
For Each cell In ws.Range("A1:A100")
If cell.Value = "Auto" Then
Range("A" & cell.Row, "E" & cell.Row, "G" & cell.Row, "I" & cell.Row, "K" &
cell.Row).Interior.Color = vbRed
ElseIf cell.Value = "Mutti" Then
Range("A" & cell.Row, "E" & cell.Row, "G" & cell.Row, "I" & cell.Row, "K" &
cell.Row).Interior.Color = vbRed
End If
Next
End Sub
解决方案
在 OP 关于避免白色的评论后编辑
你可以试试这个(评论中的解释):
Sub Schaltfläche2_Klicken()
Dim cell As Range, cell2 As Range, col As Long
Dim ws As Worksheet
Dim res As Variant
Set ws = ActiveSheet
For Each cell In ws.Range("A1:A100").SpecialCells(xlCellTypeConstants) ' loop thorugh column A not empty values
Select Case cell.Value2 ' check current column A cell value and act accordingly
Case "Auto"
col = vbRed
Case "Mutti"
col = vbGreen ' change it as per your needs
Case Else 'if no match
col = 0
End Select
If col > 0 Then ' proceed only if a color has been established
cell.Interior.Color = col
For Each cell2 In cell.Offset(, 4).Resize(4).SpecialCells(xlCellTypeConstants)
res = Switch(cell2.Value = "Mortgage", vbRed, cell2.Value = "Preferred", vbGreen, cell2.Value = "Nonpreferred", vbYellow) ' get color corresponding to cell value (change colors as per your needs)
If Not IsNull(res) Then Intersect(Range("E:E, G:G, I:I"), Rows(cell2.Row)).Interior.Color = CLng(res) ' if any valid color, apply it
Next
End If
Next
End Sub
看这里的Switch()
功能
如果您需要颜色不同的标准颜色,您可以使用RGB()
功能代替
推荐阅读
- javascript - 如何将 HTML 插入到 fullCalendar 4 中的事件标题中?
- javascript - 在 html 和 javascript 中设置文件 src 有什么区别
- postgresql - PostgreSql中是否有相当于sp_getapplock,sp_releaseapplock的?
- expo - Expo 36:无法从“node_modules/css-tree/lib/syntax/default.js”解析“../../data”
- angular - 在 InjectionToken 中使用 BehaviorSubject 有什么问题吗?
- json - 如何正确解析带有斜杠的 JSON 属性?
- django - 如果未通过 HttpResponseRedirect 填写表单,则显示用户错误消息
- c++ - Visual Studio 无法导入 Qt 库
- c# - 从数据库中以表格形式引入信息并显示它c#
- python - 来自 REST API 的 Python 请求令牌