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

问题描述 投票:2回答:2

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

我有以下内容

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用于形状)但是我到目前为止尝试的任何组合还没有工作。

excel vba excel-vba colors shape
2个回答
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

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的回答所提出的那样。

© www.soinside.com 2019 - 2024. All rights reserved.