如何使此代码运行更流畅?并在最后取消选择

时间:2019-04-16 13:05:14

标签: excel vba excel-formula

我正在尝试根据单击的每个按钮更改条形图的颜色。在代码的结尾,我不希望它在图形上选择。 这是我的按钮代码之一。 希望有什么方法可以使此代码更好,或者朝另一个方向发展。 我也在尝试将这两个代码结合起来。

Sub Add_Value_Field

    Dim pt As PivotTable
    Dim pf As PivotField
    Dim sField As String

    Set pt = ActiveSheet.PivotTables(1)
    sField = ActiveSheet.Shapes(Application.Caller).TextFrame.Characters.Text

    For Each pf In pt.DataFields
    If pf.Name <> "Values" Then
        pf.Orientation = xlHidden
    End If
    Next pf

    pt.PivotFields(sField).Orientation = xlDataField

End Sub

使用以下代码:

Sub Unselect()
    ActiveSheet.ChartObjects("Chart 1").Activate
    ActiveChart.FullSeriesCollection(1).Select
    With Selection.Format.Fill
        .Visible = msoTrue
        .ForeColor.ObjectThemeColor = msoTheColorAccent2
        .ForeColor.TintAndShade = 0
        .ForeColor.Brightness = 0
        .Transparency = 0
        .Solid
    End With
    ActiveSheet.ChartObjects("Chart 1").Activate
    ActiveChart.PlotArea.Select
    ActiveSheet.ChartObjects("Chart 1").Activate
End Sub

我希望这会使它更容易理解。

1 个答案:

答案 0 :(得分:0)

图表很难处理。我发现自己处于一种状态,即如果我在图表上不使用.Activate,则该代码将无法工作。在这种情况下,使代码更简单的方法是可行的,但不会更快。

Sub Unselect()
    Set wk = ThisWorkbook
    'We are working with charts, we have to activate the charts sometimes.
    'Adding this next two lines will let your code work from any other Sheet.
    wk.Sheets("SheetName").Activate
    wk.Sheets("SheetName").ChartObjects("Chart 1").Activate
    'Skip the select portion and go right to the format.
    With ActiveChart.FullSeriesCollection(1).Format.Fill
        .Visible = msoTrue
        .ForeColor.ObjectThemeColor = msoTheColorAccent2
        .ForeColor.TintAndShade = 0
        .ForeColor.Brightness = 0
        .Transparency = 0
        .Solid
    End With
End Sub