简体   繁体   English

如何使用VBA更改Excel 2016中插入的图片(图标)的填充颜色

[英]How to change fill color for inserted picture (icon) in Excel 2016 with VBA

Trying to add an 'Icon' (the one under the 'Insert' tab - not the conditional formatting ones) and change the fill color. 尝试添加“图标”(“插入”选项卡下的图标 - 而不是条件格式化图标)并更改填充颜色。 Using the macro recorder results in the following code: 使用宏录制器会产生以下代码:

Sub Macro1()

    ActiveSheet.Pictures.Insert( _
        "https://hubblecontent.osi.office.net/ContentSVC/Content/Download?provider=MicrosoftIcon&fileName=Document.svg" _
    ).Select
    With Selection.ShapeRange.Fill
        .Visible = msoTrue
        .ForeColor.ObjectThemeColor = msoThemeColorAccent1 'this line throws the error
        .ForeColor.TintAndShade = 0
        .ForeColor.Brightness = -0.25
        .Transparency = 0
        .Solid
    End With

End Sub

Which was expected as it's the same code used to change the fill color of a 'Shape'. 这是预期的,因为它是用于更改“形状”的填充颜色的相同代码。 The problem is that the code doesn't actually work. 问题是代码实际上不起作用。 It throws a run-time error The specified value is out of range . 它会抛出运行时错误The specified value is out of range

While trying to figure it out I noticed when right clicking on the inserted 'Icon' that the 'Fill' option is disabled, which is obviously not the case when inserting manually. 在试图解决这个问题时,我注意到当右键单击插入的“图标”时,“填充”选项被禁用,这显然不是手动插入时的情况。 I suspect it has something to do with the 'Pictures' object as opposed to 'Shapes' and/or the need to pull the image info from the interwebs, but I'm no expert. 我怀疑它与'图片'对象有关,而不是'形状'和/或需要从互联网中提取图像信息,但我不是专家。 That's why I'm here. 这就是我在这里的原因。

What I want to know is if this is doable through VBA or if I should just take a different route? 我想知道的是,如果这可以通过VBA实现,或者我应该采取不同的路线?

Try this: 尝试这个:

Sub Change_Hand_to_Yellow()
Dim shp1 As Shape
Set shp1 = ActiveSheet.Shapes("Graphic 12")
With shp1
 .Fill.ForeColor.RGB = vbYellow
End With

End Sub

I realize this answers an old question. 我意识到这回答了一个老问题。 I ran into the same issue and obviously the recorded macro was not much of help, so I had to do some tinkering. 我遇到了同样的问题,显然录制的宏没有多大帮助,所以我不得不做一些修补。 This works for me... 这对我有用......

Sub Macro1()

    Const path As String _
    = "https://hubblecontent.osi.office.net/ContentSVC/Content/Download?provider=MicrosoftIcon&fileName=Document.svg"

    Dim sheet As Worksheet
    Set sheet = ActiveSheet
    Dim insertedIcon As Shape
    Set insertedIcon = sheet.Shapes.AddPicture(path, msoFalse, msoTrue, 0, 0, -1, -1)

    With insertedIcon.Fill
        .Visible = msoTrue
        .ForeColor.ObjectThemeColor = msoThemeColorAccent1
        .ForeColor.TintAndShade = 0
        .ForeColor.Brightness = -0.25
        .Transparency = 0
        .Solid
    End With

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM