2015-11-02 126 views
3

我需要幫助編碼這個VBA的工作項目的幫助。我有一個包含所有形狀(狀態)的地圖,我有列U2:U52與州縮寫和列V2:V52與數據。我需要一個宏來運行「If Then」語句來更改顏色,並根據輸入的數據循環遍歷每個狀態(數據行)。宏改變地圖顏色(國家)

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

這是一個應該工作的簡單循環。

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 
+1

耶!這工作!謝謝! – Liz