如何通过VBA基于其他单元格值更改单元格的背景颜色
问题描述:
我在Excel表单中有两列A和B. 列是包含“是”和“否”的下拉列表。 我想从下拉列表中改变基于单元格文本值的B单元格的颜色。 例如,如果我在A1单元格中选择“是”,而B1单元格应显示为绿色。 A2,A3 ...等如何通过VBA基于其他单元格值更改单元格的背景颜色
我不是一个程序员,所以我真的在VBA coading noob。有条件编队在这种情况下也有问题。
如果有人有这个答案,那将是我的荣幸。
答
对您的代码进行了一些更改。
Sub RowFormat()
Dim A As Range
For Each A In Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
If Not IsError(A) Then
If A.Value = "Yes" Then
A.Offset(0, 1).Interior.ColorIndex = 6
ElseIf A.Value = "No" Then
A.Offset(0, 1).Interior.ColorIndex = 3
Else
A.Offset(0, 1).Interior.ColorIndex = xlNone
End If
End If
Next A
End Sub
使用条件格式。
对于“是”,使用=A1="Yes"
,
代表“否”使用=A1="No"
并且格式应用相应的格式。
编辑:
如果您正在使用Worksheet_Change事件然后在下面的代码中使用。
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub 'check for range
If Target.Value = "Yes" Then 'check if yes
Target.Offset(0, 1).Interior.ColorIndex = 6
ElseIf Target.Value = "No" Then 'check if no
Target.Offset(0, 1).Interior.ColorIndex = 3
Else
Target.Offset(0, 1).Interior.ColorIndex = xlNone
End If
End Sub
答
要使用条件格式
选择列B, 点击条件格式>
突出显示单元格规则>
平等太>键入 “是”
在下降向右选择自定义,
再次选择格式,
重复该过程“否”
会有很多更容易遵循一个快速谷歌搜索显示方法......
+0
谢谢@ User91504 –
你atempt做一些事情了吗?如果是这样,请发布您的代码。尝试使用Private Sub Worksheet_Change(ByVal Target As Range),每次更改Worksheet中的数据时,都会发生此Sub。 – AntiDrondert
你说条件格式化在这种情况下有问题,但它应该能够正确地执行你正确的操作。 – Zerk
'Sub RowFormat() Dim A As Range For Each A In Range(“A1:A”&Cells(Rows.Count,“A”)。End(xlUp).Row) If Not IsError(A)Then (“B”&C.Row&“:BB”&C.Row).Interior.ColorIndex = 6 Else 范围(“B”&C.Row&“) 如果A.Value =”Yes“Then Range :BB”&C.Row).Interior.ColorIndex = xlNone 结束如果 结束如果 下一页A 结束Sub' –