Excel-VBA 渐变色标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23349683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel-VBA gradient colorstops
提问by Aaron Thomas
What is the best way to apply horizontal gradient fill effect to a cell through macro code?
通过宏代码将水平渐变填充效果应用于单元格的最佳方法是什么?
I've set the desired gradient in Excel (right-click on cell B1, Format Cells..., Fill, Fill Effects, Two Colors, Horizontal, "Okay" all).
我已经在 Excel 中设置了所需的渐变(右键单击单元格 B1,设置单元格格式...,填充,填充效果,两种颜色,水平,“好的”全部)。
I then have the following code to find out how to represent this via code. When I step through the code, I can use the locals window to inspect the gradient and colorstops of the myrange object:
然后我有以下代码来找出如何通过代码表示这一点。当我逐步执行代码时,我可以使用 locals 窗口来检查 myrange 对象的渐变和色标:
Dim myrange As range
Set myrange = ActiveSheet.range("B1")
Using this information, I can now hard-code the information in a macro, in hopes of duplicating the gradient fill by code:
使用这些信息,我现在可以在宏中对信息进行硬编码,希望通过代码复制渐变填充:
'First, delete any previous gradient colorstops
For Each cs In myrange.Interior.Gradient.ColorStops
cs.Delete
Next
'Then, assign the desired colorstops in the gradient
With myrange.Interior.Gradient.ColorStops
.add color = 16777215
Position = 0
ThemeColor = 1
TintAndShade = 0
.add color = 7961087
Position = 0.5
ThemeColor = 0
TintAndShade = 0
.add color = 16777215
Position = 1
ThemeColor = 1
TintAndShade = 0
End With
Unfortunately, this results in something that looks totally wrong. The most obvious thing that's wrong is that the gradient is in black and white, even as I adjust the RGB values.
不幸的是,这会导致看起来完全错误的事情。最明显的错误是渐变是黑白的,即使我调整了 RGB 值。
Is there something else that should be added here?
这里还有什么需要添加的吗?
回答by teylyn
The assignment of ColorStops is not valid code. You need to add the colorstops and then set their properties. The macro recorder does it correctly.
ColorStops 的分配不是有效代码。您需要添加色标,然后设置它们的属性。宏记录器正确执行此操作。
Sub SetGradient()
Dim myrange As Range
Set myrange = ThisWorkbook.Sheets("Sheet1").Range("B1")
With myrange.Interior
.Pattern = xlPatternLinearGradient
.Gradient.Degree = 90
.Gradient.ColorStops.Clear
End With
With myrange.Interior.Gradient.ColorStops.Add(0)
.Color = 16777215
.TintAndShade = 0
End With
With myrange.Interior.Gradient.ColorStops.Add(0.5)
.Color = 7961087
.TintAndShade = 0
End With
With myrange.Interior.Gradient.ColorStops.Add(1)
.Color = 16777215
.TintAndShade = 0
End With
End Sub