0

I am trying to change the color of my bar graph based on each button that I click. And at the end of the code, I do not want it to select on the graph. Here is one of my code for the button. Hoping if there any way to make this code better or maybe go at it in a different direction. I am also trying to combine these two codes.

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

With this code:

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

I hope this made it easier to understand.

Chronocidal
  • 6,827
  • 1
  • 12
  • 26
Phiking
  • 75
  • 11

1 Answers1

0

Charts are tricky to work with. I've seen myself in a position that the code just will not work if I don't use .Activate on the chart. In this case the way to make the code simpler, but it will work the same without being any faster.

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
Ricardo A
  • 1,752
  • 1
  • 10
  • 16
  • Thank you, but for some reason, I see object not supported. Sorry, maybe I was not being too clear and specific. I want to combine this code with another code. I just edit the main post. Thank you! – Phiking Apr 16 '19 at 14:55
  • Don't forget to define your objects: `Dim wk As Workbook` – Chronocidal Apr 16 '19 at 15:10