Home » excel » Excel-VBA gradient colorstops

Excel-VBA gradient colorstops

Posted by: admin May 14, 2020 Leave a comment

Questions:

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).

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:

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.

Is there something else that should be added here?

How to&Answers:

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.

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