如果它小于F列中的值,我需要在B列中突出显示一个单元格。例如,如果单元格B2为10且F2为20,则B2应为红色。但是在B列中有空白单元格,我不想突出显示这些单元格。例如B6为空白,但F6为10。在我的代码中,B6也变为红色。
我还将如何在已经突出显示的同一行中突出显示一个单元格。例如,如果突出显示B2,则突出显示F2。
我的代码如下:
Sub threecf()
Dim rg As Range
Dim cond1 As FormatCondition, cond2 As FormatCondition
Set rg = Range("B2", Range("B2").End(xlDown))
'clear any existing conditional formatting
rg.FormatConditions.Delete
'define the rule for each conditional format
Set cond1 = rg.FormatConditions.Add(xlCellValue, xlLess, "=f2")
Set cond2 = rg.FormatConditions.Add(xlCellValue, xlEqual, "=isempty(f2)")
'define the format applied for each conditional format
With cond1
.Interior.Color = vbRed
.Font.Color = vbWhite
End With
With cond2
.Interior.Color = vbWhite
.Font.Color = vbWhite
End With
End Sub
答案 0 :(得分:1)
如我的评论中所述,使用公式。无需使用VBA
最简便的方法(推荐方式)
我建议采用这种方式,因为它考虑到了要添加的新行。
=AND(B1<F1,B1<>"")
自定义方式
=AND(B2<F2,B2<>"")
VBA方式
如果您仍然想要VBA,请尝试此
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change as applicable
Set ws = Sheet1
With ws
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
With .Range("B2:B" & lRow)
.FormatConditions.Add Type:=xlExpression, Formula1:="=AND(B2<F2,B2<>"""")"
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
End With
End With
End Sub
答案 1 :(得分:0)
转到条件格式->新规则->使用公式来确定要格式化的单元格->粘贴以下内容:=IF(AND(B2<F2,B2<>"") = TRUE,1,0)
对于F列:=IF(AND(F2>B2,F2<>"") = TRUE,1,0)
答案 2 :(得分:0)
如果您要使用VBA解决方案,请尝试不使用条件格式:
Sub StackOverflow()
Dim x As Long
With ThisWorkbook.Sheets("Stack")
For x = 1 To .Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
If .Cells(x, 2).Value <> "" And .Cells(x, 2).Value < .Cells(x, 6).Value Then
.Cells(x, 2).Interior.Color = vbRed
.Cells(x, 6).Interior.Color = vbRed
.Cells(x, 2).Font.Color = vbWhite
.Cells(x, 6).Font.Color = vbWhite
Else
.Cells(x, 2).Interior.Pattern = xlNone
.Cells(x, 6).Interior.Pattern = xlNone
.Cells(x, 2).Font.Color = vbBlack
.Cells(x, 6).Font.Color = vbBlack
End If
Next x
End With
End Sub
根据需要修改代码(如果需要,可以更改宏名称,电子表格地址和颜色)。