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

IIJ*_*FII 2 excel vba colors shape excel-vba

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

我有以下内容

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
Run Code Online (Sandbox Code Playgroud)

但是,我得到了一个

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

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

Sub*_*eer 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
Run Code Online (Sandbox Code Playgroud)