将形状颜色与单元格颜色匹配 - vba

时间:2017-12-20 10:39:21

标签: excel vba excel-vba colors shape

我希望设置一个基本循环来设置工作表中每个形状的颜色,以匹配表格中的相应单元格(条件格式化)。

我有以下

dim countryShape as shape

For Each countryShape In ActiveSheet.Shapes

countryShape.Range.Interior.Color = Application.VLookup(countryShape.Name, ActiveSheet.Range("D3:H19"), 2, 0).Interior.Color

Next countryShape

然而,我得到了一个

  

运行时错误424,'需要对象'

我猜这是与颜色应用的格式有关(即.interior.color用于单元格和.fill.forecolor用于形状)但是我到目前为止尝试的任何组合还没有工作。

2 个答案:

答案 0 :(得分:5)

要更改形状的颜色,需要更改Fill.ForeColor属性。此外,您不能使用Vlookup,因为它将返回单元格值而不是单元格颜色。

请这样试试......

Dim countryShape As Shape
Dim ColorCell As Range
For Each countryShape In ActiveSheet.Shapes
    Set ColorCell = Range("D3:D19").Find(what:=countryShape.Name, lookat:=xlWhole)
    If Not ColorCell Is Nothing Then
        'get the shape color from corresponding cell in column E
        countryShape.Fill.ForeColor.RGB = ColorCell.Offset(0, 1).Interior.Color 
    End If
Next countryShape

答案 1 :(得分:0)

你走了:

Public Sub TestMe()

    Dim shp         As Shape
    Dim fancyCell   As Range

    Dim colorR      As Long
    Dim colorG      As Long
    Dim colorB      As Long
    Dim colorFancy  As Long

    Set fancyCell = Range("A1")
    colorFancy = fancyCell.Interior.Color

    colorR = colorFancy And 255
    colorG = colorFancy \ 256 And 255
    colorB = colorFancy \ 256 ^ 2 And 255

    For Each shp In ActiveSheet.Shapes
        shp.Fill.ForeColor.RGB = RGB(colorR, colorG, colorB)
    Next shp

End Sub

形状需要RGB颜色,因此您可以从细胞中获取颜色。 RGB()会返回Long中使用的Range.Interior.Color,因此您也可以使用:       shp.Fill.ForeColor.RGB = colorFancy.Interior.Color

正如@sktneer的回答所提出的那样。