如何用EXCEL里VBA设置条件格式呢?

2025-04-14 22:15:31
推荐回答(1个)
回答1:

下面是一个将0~9的数字自动设定格式的例子,在Worksheet_Change加入如下代码:
Private Sub Worksheet_Change(ByVal Target As Range)

On Error GoTo line1 '当出现错误时转到line1语句处执行.这里是退出循环

If Target.Value <= 9 And Target.Value >= 0 Then
'如果单元格的值小于或等于9并且大于或等于0就进入循环
Select Case Target.Value
Case 9
Target.Font.ColorIndex = 3 '此语句为设置字体颜色的
Target.Interior.ColorIndex = 5 '此句是设置单元格背影颜色的,下面的可依此法添加。
Case 8
Target.Font.ColorIndex = 45
Case 7
Target.Font.ColorIndex = 8
Case 6
Target.Font.ColorIndex = 7
Case 5
Target.Font.ColorIndex = 23
Case 4
Target.Font.ColorIndex = 27
Case 3
Target.Font.ColorIndex = 5
Case 2
Target.Font.ColorIndex = 12
Case 1
Target.Font.ColorIndex = 9
Case Else 'Case 0 (也可以换成前面的这句.之所以这样做,是为了防止有一些意想不到的事情发生)
Target.Font.ColorIndex = 15
End Select
End If
line1:
End Sub
你可以跟据需要修改。