问题
My data bar looks good (solid) when executing the VBA command. However, after I saved the file and reopened, data bar changed to gradient automatically. How do I avoid this?
Before saving and reopening file:

After saving and reopening file:

Here's the code I used:
Dim DB As Databar
Set DB = Range("K2:K10").FormatConditions.AddDatabar
With DB
.BarFillType = xlDataBarSolid
.BarBorder.Type = xlDataBarBorderSolid
With .BarBorder.Color
.Color = 15698432
End With
With .BarColor
.Color = 15698432
.TintAndShade = 0
End With
End With
With DB.BarColor
.Color = 15698432
.TintAndShade = 0
End With
With Range("K2:K10").FormatConditions(1)
.MinPoint.Modify newtype:=xlConditionValueAutomaticMin
.MaxPoint.Modify newtype:=xlConditionValueAutomaticMax
End With
回答1:
First of all, you have this twice; either one will suffice.
...
With .BarColor
.Color = 15698432
.TintAndShade = 0
End With
End With
With DB.BarColor
.Color = 15698432
.TintAndShade = 0
End With
...
Also, and this is VERY IMPORTANT: In my experience, once you've difined a Databar--you are done with the fill, and it will not change. If needed, you can delete the Databar and set it up again:
With Range("K2:K10")
For i = .FormatConditions.Count To 1 Step -1
.FormatConditions(i).Delete
Next
'Create a DataBar object ' as you've been doing it already
...
End With
Hope this works for you.
回答2:
I have created test Sub, placed in Sheet1 VBA code module and ran it in Excel 2010 (see the code snippet below). Everything works fine as expected.
Sub FormatDatabar()
Dim DB As Databar
Set DB = Range("K2:K10").FormatConditions.AddDatabar
With DB
.BarFillType = xlDataBarSolid
.BarBorder.Type = xlDataBarBorderSolid
With .BarBorder.Color
.Color = 15698432
End With
With .BarColor
.Color = 15698432
.TintAndShade = 0
End With
End With
'this is redundant
'With DB.BarColor
'.Color = 15698432
'.TintAndShade = 0
'End With
With Range("K2:K10").FormatConditions(1)
.MinPoint.Modify newtype:=xlConditionValueAutomaticMin
.MaxPoint.Modify newtype:=xlConditionValueAutomaticMax
End With
End Sub
It also works well with Hex color index:
Sub FormatDatabar()
Dim DB As Databar
Set DB = Range("K2:K10").FormatConditions.AddDatabar
With DB
.BarFillType = xlDataBarSolid
.BarBorder.Type = xlDataBarBorderSolid
With .BarBorder.Color
'Green color
.Color = &HC0F0&
End With
With .BarColor
.Color = &HC0F0&
.TintAndShade = 0
End With
End With
With Range("K2:K10").FormatConditions(1)
.MinPoint.Modify newtype:=xlConditionValueAutomaticMin
.MaxPoint.Modify newtype:=xlConditionValueAutomaticMax
End With
End Sub
You probably should check the settings on your machine. Kind regards,
来源:https://stackoverflow.com/questions/27608334/how-to-apply-solid-colors-to-data-bar-in-excel-vba