|让我们画一个Monalisa画,然后使用VBA留下毕加索。

准备好了,准备好……等等!等待!稍安毋躁。我们将要使用VBA进行条件格式设置,这比绘画要容易吗?形的鸟。

VBA条件格式的通用语法

If condition than

Range(range).Interior.ColorIndex= 1-56

根据条件进行条件检查,然后使用Range对象的属性.iteriour.colorindex格式化范围。颜色索引具有56种颜色。去和他们一起玩洒红节,探索哪个数字代表哪种颜色。

现在让我们以一个示例====来理解它:示例:VBA代码有条件地格式化单元格

1

因此,在这种情况下,我们有一个随机年龄段的人列表。

只看名字就能告诉年龄组一个人有多容易。

现在,我要使用VBA格式,如果他成年,则要使用名称RED,如果他是十几岁,则要使用YELLOW,如果他是KID,则要使用GREEN,如果单元格为空,则不使用。

Sub FormatUsingVBA()

Dim rng As Range

Dim lastRow As Long

lastRow = Cells(Rows.Count, 3).End(xlUp).Row

Set rng = Range("C2:C" & lastRow)For Each cell In rng

If cell.Value2 = "Adult" Then

Range(cell.Address).Offset(0, -2).Interior.ColorIndex = 3

ElseIf cell.Value2 = "KID" Then

Range(cell.Address).Offset(0, -2).Interior.ColorIndex = 4

ElseIf cell.Value2 = "Teenager" Then

Range(cell.Address).Offset(0, -2).Interior.ColorIndex = 6

Else

Range(cell.Address).Offset(0, -2).Interior.ColorIndex = 0

End If

Next cell

End Sub

为了直接从工作表运行此代码,我在同一工作表上绘制了一个按钮,并将此宏分配给它。现在,只要您单击“格式”按钮,您的代码就会运行并根据名称年龄使用颜色更新名称单元。怎么样?让我们找出答案。

代码说明:

Dim rng As RangeDim lastRow As LongThese two lines are variable declarations.

rng for Range that holds the age group and lastRow to get last nonblank row number.
lastRow = Cells(Rows.Count, 3).End(xlUp).RowThis line returns last row number in lastRow Variable.
Set rng = Range("C2:C" & lastRow)This line sets the range starting from C2 and to the last row.

It makes your code dynamic. You add new rows to your data and it will detect and will store in new range in rng variable.
For Each cell In rng

If cell.Value2 = "Adult" Then

Range(cell.Address).Offset(0, -2).Interior.ColorIndex = 3

ElseIf cell.Value2 = "KID" Then

Range(cell.Address).Offset(0, -2).Interior.ColorIndex = 4

ElseIf cell.Value2 = "Teenager" Then

Range(cell.Address).Offset(0, -2).Interior.ColorIndex = 6

Else

Range(cell.Address).Offset(0, -2).Interior.ColorIndex = 0

End If

Next cell

这是主要部分。

For Each cell In rng

第一行将循环运行到您范围内的所有单元格。如果cell.Value2 =“ Adult”,则下一行是条件检查。它检查当前单元格值是否为Adult。

如果是,则运行下一行,否则跳至下一条if语句。Range(cell.Address).Offset(0,-2).Interior.ColorIndex = 3现在,如果IF条件返回TRUE,则此行将单元格颜色设置为用于RED的ColorIndex 3。

类似地,以下IF语句将运行并按照指定的方式执行操作。

是的,您可以有条件地使用VBA格式化范围。 Range对象的内部方法控制其他许多格式属性。您应该和他们一起玩,不会有任何危害,但是您一定会学到的。如果您遇到的困难比我在这里遇到的困难更大。在评论部分提出您的问题。

热门文章:

link:/ formulas-and-functions-vlookup-function简介[如何在Excel中使用VLOOKUP函数]