单击单元格时更改形状颜色

时间:2016-04-19 20:42:46

标签: excel-vba colors shapes choropleth vba

我正在寻找一些代码,可以在单击单元格时更改形状的颜色。 示例形状是S_IRL,它是Ireland,位于单元格B22中。

我想要发生的是,如果Cell B22然后形状S_IRL从蓝色变为红色。然后,如果单击具有国家/地区的另一个单元格,则相应的形状将变为红色,之前的形状将返回到之前的颜色。 任何帮助将不胜感激 enter image description here

1 个答案:

答案 0 :(得分:1)

您可以在工作表的代码中添加一个新的子例程,该子例程将在工作表上的选择发生变化时触发:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim strShapeName As String 'Variable to hold the shape name
    Dim shp As Shape 'Variable to hold a shape object

    'Detect if the click was in range A:C
    If Not Intersect(Target, Range("A:C")) Is Nothing Then

        'Boom... set all the shapes to blue
        For Each shp In Me.Shapes
             If Left(shp.Name, 2) = "S_" Then shp.Fill.ForeColor.RGB = RGB(0, 0, 255)
        Next shp        

        'Grab the shape name from Column A
        strShapeName = Cells(Target.Row, 1).Value

        'Set the color of the shape to red
        Shapes(strShapeName).Fill.ForeColor.RGB = RGB(255, 0, 0)
    End If
End Sub

这将检测选择更改是否属于A,B或C列中的单元格。如果是,它将从A列中获取形状的名称,然后将该形状的颜色设置为红色。