VBA条件格式取决于度量标准类型

问题描述 投票:-1回答:1

我一直在尝试创建一个VBA代码,该代码将根据指标的升序或降序自动将适当的条件格式应用于指标结果。尝试使用vlookup在表中搜索指标代码,并输出value =降序/升序,并仅将指标分配给适当的条件格式,而不是整列。

因此,如果我们在表格Sheets(“ Formulas”)。Range(A:N)中查找单元格E2,并且发现它的值为Descending,并且由于“ result”不等于ascdes,那么我想编写条件代码格式化单元格$ AA $ 2中的降序指示符。所有范围内的指标都会发生这种情况。

我只设法创建了以下代码,该代码创建了降序条件格式,但适用于AA列中的所有单元,而不是仅适用于AA2。

指标混杂在一起,因此手动放置CF会花费很多时间,如果有人对指标A-Z进行排序并保存,他将只需要运行可修复CF的宏,而不是撤消排序更改。

Sub ConditionalFormatting()

Dim code As Range 'searched values
Dim ascdes As String 'variable that indicates values are ascending or descending
Dim table As Range 'table where we check if code is ascending or descending
Dim cond1 As FormatCondition, cond2 As FormatCondition, cond3 As FormatCondition
Dim rg As Range
Dim result As String

Set rg = Range("$AA$2:$AA$300")

'clear any existing conditional formatting
rg.FormatConditions.Delete

'vlookup conditions
Set code = Range("E2")
Set table = Sheets("Formulas").Range("A:N")

'holds value ascendat for comparison purposes
rosmal = Sheets("Formulas").Range("O2")

result= Application.VLookup(code, table, 14, 0)

If result = ascdes Then

'define the rule for each conditional format
Set cond1 = rg.FormatConditions.Add(xlCellValue, xlGreaterEqual, "=$Q2") 'Green
Set cond2 = rg.FormatConditions.Add(xlCellValue, xlBetween, "=$O2", "=$P2") 'Amber
Set cond3 = rg.FormatConditions.Add(xlCellValue, xlLessEqual, "=$N2") 'Red

'define the format applied for each conditional format
With cond1
.Interior.Color = RGB(0, 176, 80) 'vbGreen
.Font.Color = vbBlack
End With

With cond2
.Interior.Color = RGB(255, 204, 0) 'vbYellow
.Font.Color = vbBlack
End With

With cond3
.Interior.Color = RGB(255, 0, 0) 'vbRed
.Font.Color = vbBlack
End With

Else

    'define the rule for each conditional format
Set cond1 = rg.FormatConditions.Add(xlCellValue, xlGreaterEqual, "=$N2") 'Red
Set cond2 = rg.FormatConditions.Add(xlCellValue, xlBetween, "=$O2", "=$P2") 'Amber
Set cond3 = rg.FormatConditions.Add(xlCellValue, xlLessEqual, "=$Q2") 'Amber

'define the format applied for each conditional format
With cond1
.Interior.Color = RGB(0, 176, 80) 'vbGreen
.Font.Color = vbBlack
End With

With cond2
.Interior.Color = RGB(255, 204, 0) 'vbYellow
.Font.Color = vbBlack
End With

With cond3
.Interior.Color = RGB(255, 0, 0) 'vbRed
.Font.Color = vbBlack
End With

End If

End Sub

几乎忘了使用过的excel版本是2013,无法安装任何外部插件。

谢谢,

excel vba conditional-formatting
1个回答
0
投票

我设法通过创建变量并在Cells中使用它来在电子表格中移动来解决了这个问题。还添加了do while循环,该循环增加可变值,直到达到特定值为止。

© www.soinside.com 2019 - 2024. All rights reserved.