我被困住了,我不知道是否有任何解决方案,因为我已经尝试了很多但仍然失败。
我正在尝试添加条件格式,因此如果B列中的单元格等于或小于A列中的伙伴单元格的19%,则B列中的单元格变为黄色。因此在上面的示例中,单元格B1应变为黄色因为$ 19,000小于或等于100,000美元的19%。
我需要通过excel vba添加此条件格式。我尝试在下面添加vba代码,但是B1:B3中所有单元格的条件格式化公式都被$A1*0.19
卡住了。我需要B1条件格式化公式为$A1*0.19
,然后B2条件格式化公式将为$A2*0.19
等等。顺便说一句,我有大约350行,不仅仅是3.即便如此,我的vba代码变为$A521325*0.19
或者与真实或实际相关的东西。
With Sheet1.Range(Sheet1.Cells(1, 2), Sheet1.Cells(3, 2))
daformula = "=$A1*0.19"
.FormatConditions.Add Type:=xlCellValue, Operator:=xlLessEqual, Formula1:=daformula
.FormatConditions(.FormatConditions.Count).SetFirstPriority
.FormatConditions(1).Interior.PatternColorIndex = xlAutomatic
.FormatConditions(1).Interior.ThemeColor = xlThemeColorAccent2
.FormatConditions(1).Interior.TintAndShade = -0.249946592608417
.FormatConditions(1).StopIfTrue = False
End With
这个想法是在运行将条件格式添加到工作表的宏之后,当用户更改B列中的一个单元格时,颜色会消失或重新出现,具体取决于用户将单元格更改为的值(条件格式)必须仍然有效)
答案 0 :(得分:2)
尝试,
With ActiveSheet.Cells(1, 2).Resize(3, 1)
.FormatConditions.Add Type:=xlExpression, Formula1:="=$B1<=($A1*0.19)"
.FormatConditions(.FormatConditions.Count).Interior.Color = 65535
End With
是否添加其他详细信息(如.SetFirstPriority
或.StopIfTrue
)在某种程度上取决于其他CF规则如何影响相同的单元格。
答案 1 :(得分:1)
您可以创建一个事件来监视A列中的任何更改(将此代码放在Sheet1对象中)
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 1 Then
'run code to add conditional formatting
condFormat Target
End If
End Sub
现在我们只需要更改您的上述代码以接受目标,并且只为B列中的等效单元格添加格式
Public sub condFormat (Target as range)
With target.offset(0,1)
daformula = "=" & target.address & "*0.19"
.FormatConditions.Add Type:=xlCellValue, Operator:=xlLessEqual, _
Formula1:=daformula
.FormatConditions(.FormatConditions.Count).SetFirstPriority
.FormatConditions(1).Interior.PatternColorIndex = xlAutomatic
.FormatConditions(1).Interior.ThemeColor = xlThemeColorAccent2
.FormatConditions(1).Interior.TintAndShade = -0.249946592608417
.FormatConditions(1).StopIfTrue = False
End With
end sub
我没有考虑过一次改变超过1个细胞,但这将解决你的挑战
答案 2 :(得分:0)
从VBA创建条件格式时,相对于条件格式公式的单元格选择至关重要。
如果条件格式化公式仅访问同一行上的值,请尝试使用ActiveSheet.cells(1,1).select;如果引用上述行的值,则尝试使用ActiveSheet.cells(2,1)。