用于更改地图颜色的宏(状态)

时间:2015-11-02 21:57:37

标签: excel vba excel-vba loops

我需要帮助将此VBA编码为工作项目。我有一个名为所有形状(状态)的地图,我有U2列:U52,状态缩写,列V2:V52,数据。我需要一个宏来运行“If Then”语句来更改颜色并根据输入的数据循环遍历每个State(数据行)。

Sub map1()

Dim Rng As Range
Dim ShapeName As String
Dim SHP As Shape

ShapeName = "AL"

Set Rng = ThisWorkbook.Worksheets("Sheet1").Range("V2")
Set SHP = Rng.Parent.Shapes(ShapeName)


If Rng.Value <= 1.6 Then
SHP.Fill.ForeColor.RGB = RGB(255, 0, 0) 'Red

End If

If Rng.Value > 1.6 And Rng.Value < 2.4 Then
SHP.Fill.ForeColor.RGB = RGB(0, 255, 0) 'Green

End If

If Rng.Value >= 2.4 Then
SHP.Fill.ForeColor.RGB = RGB(255, 255, 0) 'yellow

End If

End Sub

它的编写方式仅适用于一种形状,如何更改它以运行所有状态而不编码52次?

1 个答案:

答案 0 :(得分:1)

这是一个应该有效的简单循环。

Sub map1()

Dim Rng As Range
Dim ShapeName As String
Dim SHP As Shape

For i = 2 to 52

    ShapeName = ThisWorkbook.Worksheets("Sheet1").Range("U" & i).Value

    Set Rng = ThisWorkbook.Worksheets("Sheet1").Range("V" & i)
    Set SHP = Rng.Parent.Shapes(ShapeName)

    If Rng.Value <= 1.6 Then
        SHP.Fill.ForeColor.RGB = RGB(255, 0, 0) 'Red
    ElseIf Rng.Value > 1.6 And Rng.Value < 2.4 Then
        SHP.Fill.ForeColor.RGB = RGB(0, 255, 0) 'Green
    ElseIf Rng.Value >= 2.4 Then
        SHP.Fill.ForeColor.RGB = RGB(255, 255, 0) 'yellow
    End If
Next i

End Sub