如何将纯色应用于Excel VBA中的数据栏?

时间:2014-12-22 18:24:19

标签: excel vba excel-vba colors bar-chart

执行VBA命令时,我的数据栏看起来很好(可靠)。但是,在我保存文件并重新打开后,数据栏会自动更改为渐变。我该如何避免这种情况?

保存并重新打开文件之前:

Before saving the file

保存并重新打开文件后:

After saving the file

这是我使用的代码:

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

2 个答案:

答案 0 :(得分:2)

首先,你有两次;任何一个都足够了。

...
    With .BarColor
        .Color = 15698432
        .TintAndShade = 0
    End With
End With

With DB.BarColor
    .Color = 15698432
    .TintAndShade = 0
End With
...

此外,这非常重要:根据我的经验,一旦你对Databar有所了解 - 你就完成了填充,它不会改变。如果需要,您可以删除数据条并重新设置:

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

希望这适合你。

答案 1 :(得分:1)

我创建了测试Sub,放置在Sheet1 VBA代码模块中并在Excel 2010中运行它(请参阅下面的代码片段)。一切都按预期工作正常。

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

它也适用于Hex颜色索引:

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

您可能应该检查机器上的设置。亲切的问候,