How to iterate through multiples charts - excel

I need to iterate and modify properties of some charts one by one, but for that I use ActiveChart ex.:
Target_str = ActiveChart.SeriesCollection(2).DataLabels.Item(1).Caption
Target = CDbl(Target_str)
To make my charts active I try to select them one by one:
For i = 1 To ActiveWorkbook.Sheets(2).ChartObjects.Count
ActiveWorkbook.Sheets(2).ChartObjects(i).Chart.Select
'...
Next i
But I get the following message in debug:
Run-time error '1004':
Unable to get the Select property of the Chart class
How can I make those charts active one by one, what am I doing wrong in the above code.
Can I use other alternative?

What about this?
ActiveWorkbook.Sheets(2).ChartObjects(i).Select

Related

VBA skipping code based on previous error

I think I am missing something obvious but have been looking at it for so long I think I may be blind to it.
I have a sheet coded to create a pivot table from a downloaded report and apply specific filters to the pivot table - which I am aware will have some instances where there is only 1 item in the filter list so cannot apply and returns an error.
I have managed to add 'On Error GoTo...' a line past the code I know will not be able to process.
However, I also have a second Pivot Table on the same sheet which applies the same filter but in reverse - i.e. the filter will usually have 2 items, so the 2 pivot tables end up showing the breakdown of the contents of each item.
The problem is 'On Error GoTo...' is not working on the second item.
I have the GoTo locations name differently - the first pivot GoTo = 'NoOKL:' and the second = 'NoOKS:'.
Because an error on the first Pivot will mean an error on the second every time I am trying to get around this by adding 'P = 1' to the error handling of the first Pivot and then added the code below for the second:
If P = 1 Then GoTo NoOKS
With ActiveSheet.PivotTables("PivotTable11").PivotFields("CATEGORY")
.PivotItems("OKL_CONTRACTS").Visible = False
End With
ActiveSheet.PivotTables("PivotTable11").PivotFields("CATEGORY"). _
EnableMultiplePageItems = True
NoOKS:
End If
I have tried moving the GoTo location 'NoOKS' both inside the If statement and outside but get the same result.
Any help would be appreciated.
Here's an example of what your code might look like if you omit all GoTo's.
If P = 1 Then
With ActiveSheet.PivotTables("PivotTable12").PivotFields("CATEGORY")
.PivotItems("OKL_CONTRACTS").Visible = False
.EnableMultiplePageItems = False
End With
Else
With ActiveSheet.PivotTables("PivotTable11").PivotFields("CATEGORY")
.PivotItems("OKL_CONTRACTS").Visible = False
.EnableMultiplePageItems = True
End With
End If
This code presumes that you have 2 pivot tables of which you want to hide one subject to the number of items it will display (presumed to be P) and set the EnableMultiplePageItems property differently. This doesn't make much sense in the above example but the objective is to show the use of If and Else instead of GoTo.
I point out that EnableMultiplePageItems = (P = 1) would also set the property to either True or False depending upon the evaluation of the statement (P = 1). In the above example the property belongs to different objects but if you have to set the same property for the same object to different values in your project depending upon the value of P that method will avoid even the use of If, not to mention GoTo and reduce the amount of code as well.

Report Filter on a single item in pivot table

I have the following code to ensure that only a single value is selected on the relevant pivot field - however I keep getting the error "unable to set the currentpage property of the pivot field" - I don't understand why as I used a the same code for a different filter.
Sub filters()
Dim PRC As PivotField
Sheets("workings-calc").Select
Set PRC = ActiveSheet.PivotTables("PivotTable3").PivotFields("PR_CD")
PRC.ClearAllFilters
PRC.CurrentPage = "PR-500001"
End Sub
Appreciate any help on this. Have spent far too long trying to get this to work without success :/
The following code works and gets me the desired output.
for each itm1 in prc.pivotitems
if item 1.name = "PR-500001" then
else
itm1.visible = false
next
the above code leaves only the filter specified selected on the pivot field.
Thanks for all the input.

Hide and unhide series in a chart based on their name and i have error 1104

I am trying to hide and unhide series in a chart based on their name using excel vba and I have a error 1004 invalid parameter after the first run of the for cycle.
Sub macroChart3()
'
' macroChart3 Macro test
'
Dim i, n As Integer
For i = 1 To 96 Step 1
If ActiveChart.SeriesCollection(i).Name = "*contracted*" Then
ActiveChart.SeriesCollection(i).IsFiltered = False
Else
ActiveChart.SeriesCollection(i).IsFiltered = True
End If
Next i
End Sub
SeriesCollection.IsFiltered method seemed to toggle this check box:
I couldn't use that. I wanted to record macro and see if any other method is used but the checkbox is gone in 2010:
So it might be not possible to use that anymore. If you are using a different version where this method exists you might have a problem that the series is not listed in in seriesCollection anymore:
Remarks from MSDN
When a user filters out a series, the series IsFiltered property switches to True, and the series is transferred out of its parent SeriesCollection.
See if you can use FullSeriesCollection instead when you change the visibility of series:
ActiveChart.FullSeriesCollection(2).IsFiltered = True
If that doesn't work you might add and remove ranges instead of hiding them.
UPDATE:
Run your macro in step mode (F8) so you have full visibility of the execution steps. Add your evaluated expressions (ones that are used within IFs) to see their result and you will find out if they are incorrect or are evaluated as FALSE and try to figure out why.
And don't forget to up vote the answer if you find it helpful.
thanks for the quick reply, the error is fixed, but still not all the series are processed by the if clauses in the for cycle, for example this statement:
Else
ActiveChart.SeriesCollection(i).IsFiltered = True
End If
Isn't executed and I don't understand why.

Accessing PivotChart SeriesCollection with a Sub

I am quite new to VBA. I have written a macro which creates about 10 pivot charts and some normal charts after filtering and cutting some data from a database spreadsheet. I now want to write a sub which goes through applying the same formatting to each one. The sub is as follows:
Sub FormatChart(Cht As ChartObject, title As String)
Cht.Activate
MsgBox ActiveChart.SeriesCollection.Count
With ActiveChart
.HasTitle = True
.ChartTitle.Text = title
.Axes(xlValue).HasMajorGridlines = False
End With
ActiveChart.SeriesCollection(1).Select
With Selection.Format.Fill
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 182, 0)
End With
End Sub
I originally didn't include all the activates and selects, but couldn't get the macro to work without them and don't see it as the end of the world - the datasets are never going to be massive so speed isn't so much of a concern, and I disable screenupdating so that users can't click on cells/other objects and disrupt the macro as it runs.
Here's my problem. If I take out the second With loop, everything proceeds perfectly and the gridlines are removed and the title is added. However, whenever I try to edit the colours of columns with the above I get Run time error '1004': Invalid parameter. I've also tried keeping the content of the second with loop inside the first but then moved it out to try using selection to see if it made a difference.
I've fiddled around quite a bit and recorded various macros changing the colour of the chart in question, but I think the problem might be to do with referencing SeriesCollection as when I try to debug with
MsgBox ActiveChart.SeriesCollection.Count
I get "0".
Please let me know if I'm missing the point - as I said I am new to VBA and am trying to learn as much as possible :)
EDIT: The solution was that I was passing each chart to the above sub after I had created the chart, but before I had set a data source for the chart. Doh!
This obviously meant that there were no seriesCollections for that chart, hence the error I was getting.
I marked Joehannah as answering the question (even though it isn't technically the solution) because it made me check my code and notice that the above could be causing the problem - if I shouldn't do that someone please tell me and I'll try to fix it!
You are better off using Set cht = (create chart object) for each chart and then Immediately calling the format method passing in cht.
I have been told to post my own answer since I figured out the issue.
I was passing each chart to this function just after creating it, as follows:
Set ptr1 = Sheets("withinBRSPivots").PivotTables("UniqueClicks").TableRange1
Set cht1 = Sheets("BRS Overview").ChartObjects.Add(Left:=950, Top:=500, _
Width:=400, Height:=300)
cht1.Name = "UCChart"
Charter.FormatChart cht1, "Average Number of Unqique Clicks"
I then set the source data for the chart after doing the above. This meant that when the chart was passed to my chartformat sub, it had no source data. This is what resulted in being able to edit the title and gridlines, but not the seriesCollection. The fix was to just move the FormatChart sub line to after I had set the source data.
Many thanks to everyone who posted answers!

Setting VBA Excel Chart Legend Position Property in MS Access not working

This is a very strange issue I am facing for a while now, when creating some Excel worksheets programmatically from MS Access 2003.
Using this VBA-Code snippet I am not able to set the Position property of an Excel's Legend object (variable definitions and so on are left out to ease understanding).
...
Set ChartObject = myWorksheet.ChartObjects.Add(myRange.Left, myRange.Top, myRange.width, myRange.Height)
Set Chart = ChartObject.Chart
Chart.HasLegend = True
'This line raises an error:
Chart.Legend.Position = -4107 '=xlLegendPositionBottom
...
MS Access always raises the Error 1004:
"Unable to set the Position property of the Legend class"
It confuses me that I can use the exact same code from within Exel VBA and it just works. What confuses me even more is that the property HasLegend can be set whithout any error ocurring.
Someone has a hint to solve this issue?
After building a generic version of my code I found that in Office/Excel 2003 I have to populate my Series of data to the chart before changing the Legend's position. Probably the object hasn't been initiated before. My Code should therefore look like this:
...
Set ChartObject = myWorksheet.ChartObjects.Add(myRange.Left, myRange.Top, myRange.width, myRange.Height)
Set Chart = ChartObject.Chart
Chart.HasLegend = True
...
Chart.SeriesCollection.Add myRange, 1 '=xlRows
'Now this works:
Chart.Legend.Position = -4107 '=xlLegendPositionBottom

Resources