Cannot delete a chart series using VBA in Excel 2010 - excel

I have a VBA macro written in Excel 2003 which has worked perfectly well in Excel 2003 and 2007. However, it falls over in Excel 2010 and I cannot tell why.
The macro updates the series in a chart after the user has added or removed data. The first step (after data validation) is to delete all but the first series in the chart.
'clear all chart series except for series 1
Do While theChart.SeriesCollection.Count > 1
theChart.SeriesCollection(2).Delete
Loop
Execution halts in the very first iteration of the loop, with the error dialog "Method 'delete' of object 'series' failed."
I thought perhaps the object model had changed in Excel 2010, so I used the macro recorder to record the action of deleting a series:
ActiveSheet.ChartObjects("Plant Feed").Activate
ActiveChart.SeriesCollection(3).Select
Selection.Delete
Running the recorded macro (with Series 3 re-instated obviously) stops on the second line with "Method 'select' of object 'series' failed."
I then added an object variable and some msgbox lines to try to debug the problem:
Dim theSeries As Series
ActiveSheet.ChartObjects("Plant Feed").Activate
MsgBox (ActiveChart.SeriesCollection(3).Name)
Set theSeries = ActiveChart.SeriesCollection(3)
MsgBox (theSeries.Name)
theSeries.Delete
The object variable sets correctly and the message boxes give the right output, but it still falls over on theSeries.delete.
Finally, I repeated all of the above using a brand new chart created in Excel 2010, just in case it was a legacy problem from 2003, but I got the same error.
I am tearing my hair out. I've searched on line for solutions to no avail, which is what led me to this Stack Overflow site. I would appreciate any help that anyone can offer.
Regards,
Darren

Have you tried it this way instead?
For x = theChart.SeriesCollection.Count To 2 Step -1
theChart.SeriesCollection(x).Delete
Next x

Delete items from the beginning of the collection, there will always be a first element, until you deleted them all.
Do While theChart.SeriesCollection.Count > 1
theChart.SeriesCollection(1).Delete
'theChart.SeriesCollection(2).Delete
Loop

Related

PivotItems("(blank)").Visible = False gives error 400 on one computer but runs without error on another

I have a macro which helps users set and clear filters on a PivotTable. The macro has been working fine with my whole office for months. Then for seemingly no reason, one persons computer started getting error 400 on the line:
MySheet.MyPivotTable.MyPivotField.PivotItems("(blank)").Visible = False
For reference, the actual line is pf_New.PivotItems("(blank)").Visible = False where pf_New is a PivotField Object defined as Me.PivotTables("Usage").PivotFields(Sheet1.[UsedOn6].Column - 6 + new_machine) where new_machine is an integer argument of the sub.
There are certainly blank items in the table's source data for that field. The line works on my computer and I can confirm that it is removing blank items from the table. But when I move to my co-workers computer and run the line, it gives error 400.
Does anyone have any ideas behind the cause, or suggestions on how to avoid the error? Is there an alternate method to filtering blank rows from this pivotfield?
After doing more investigating on the PC causing problems, I found that the cause of the error was a combination of other settings and code that failed to set up the table properly for filtering.
In the pivot table options, "Save source data with file" was unchecked and "Refresh data when opening the file" was unchecked. This was to cut down on file size and reduce the delay when opening the file.
But having those two options off means that the pivot table has no data when opening the file. Interacting with the table in Excel will display the error "The PivotTable report was saved without the underlying data. Use the Refresh Data command to update the report" but when interacting with it in VBA you instead get the error "Out of Memory" or "400".
To avoid this issue, use ThisWorkbook.RefreshAll or YourPivotTable.RefreshTable before attempting to apply or change any filters.
In my file, the reason why it happened to only one person and not the rest of my co-workers was because my Workbook_Open event does have the line ThisWorkbook.RefreshAll after a bunch of other processes. For an unknown reason that I am still investigating, this one person's PC was skipping that line.

Runtime Error 1004: Unable to get the PivotTables property of the worksheet class. My recorded macro doesnt run?

This is driving my nut, i spent the last hour trying to find a fix to these with no success.
I have a few PivotCharts in a worksheet and i need to refresh them manually.
So i tried to record a macro doing a left click and a refresh, here is the result of the macro :
ActiveChart.PlotArea.Select
ActiveChart.ChartArea.Select
ActiveSheet.PivotTables("PivotChartTable5").PivotCache.refresh
ok, when i tried to run the the macro, i have the following error :
And if i get rid of the first 2 lines of the macro, select one chart and run the macro (the last line only) i have the following error :
I need help.
I tried to replace the activeSheet with the current sheet (Sheets.("mysheet")), doesnt help :(
One thing, if i click on the chart, i dont find the PivotChartTable5 name anywhere, my charts are called something like Chart 12 or whatever the number.
Thanks

Error while creating error bars in Excel with VBA

I want to insert error bars into a clustered column chart in excel using macros. Whenever I do, an error is thrown.
I have a much larger program that takes and sorts data into a couple column charts, and I want to add error bars to them. In an attempt to troubleshoot, I stripped the program way back to just the part that adds the error bars in a separate sheet (code below). I made a simple column chart, selected it and tried to run the program, but it threw an Application Defined error.
Then I tried recording a macro, and that also failed (with a "Method SetElement of Object _Chart Failed" error).
I've Googled around a bit, and found next to nothing (only examples of how to use my first method, close to exactly the same as mine), but also I am relatively new to VBA and might just not know the correct words to google.
Here is my code:
'The code that I had written
Sub AddErrorBars()
'Adds error bars (Standard deviation) to selected chart
ActiveChart.SeriesCollection(1).ErrorBar Direction:=xlY, _
Type:=xlErrorBarTypeStDev, Include:=xlBoth
End Sub
'The code generated by recoring a macro
Sub AddErrorBarsV2()
'Adds error bars (Standard deviation) to selected chart
ActiveChart.SetElement (msoElementLineHiLoLine)
End Sub
One odd thing, the Include enum in first sub (xlBoth) was listed as xlErrorBarIncludeBoth in the MO documentation website, but the listed value is 1, which is the value of xlBoth according to the debugger, xlErrorBarIncludeBoth is empty. Using xlNone doesn't spit out an error, but also doesn't generate error bars. Ive also tried changing the Direction, but that doesnt seem to help.
Is there something I am doing wrong, or perhaps is it the way my data is formatted? Does anyone else seem to have the same issue?
If you have the chart selected, then ActiveChart.SetElement (msoElementErrorBarStandardError) will work fine. However, you should call the chart by name, like so:
ThisWorkbook.Worksheets("Sheet1").ChartObjects("Chart 1").Chart.SetElement (msoElementErrorBarStandardError)

How to position a chart copied from excel into powerpoint using CommandBars?

I am trying to copy some charts (embedded) in different worksheets of an excel workbook using vbscript into different slides of a powerpoint. I would like to keep the link between the excel sheet and the powerpoint while doing so and therefore I used the below piece of code that allows me to keep formatting and link (instead of a simple paste or PasteSpeical. Is there any other way?) :
For i = 1 to TotalNumWorkSheets 'I iterated with indices.
Set pptSlide = pptPres.Slides.Add(i, 11) 'There is one opening slide before this.
set ws = wb.Worksheets(i)
ws.ChartObjects(1).Chart.ChartArea.Copy
pptApp.CommandBars.ExecuteMso("PasteExcelChartSourceFormatting")
pptApp.CommandBars.ReleaseFocus
With pptSlide
.Shapes.Title.TextFrame.TextRange.Text = objCurSheet.Name
'Adding some more textboxes here. Working fine. Position checks out in PPT.
.Shapes(.Shapes.Count).Left = 20 'Doesn't work for all slides.
End With
Next
The code works and copies all the charts, creates titles, adds new text as expected, but I am not able to position the charts on individual slides because after the ExecuteMso command, I don't know how to access the reference to the chart. I read in one of the SO posts that pasting using this method looses the chart selection but you can access the last .Shapes object since pasting always adds the object to the end of the list. Is that always the case? I tried accessing and positioning my chart by accessing the last object but it only works for the first slide of the loop (i.e. the first chart pasted is shifted to Left=20). The rest all charts in other slides are centered. Can someone explain where and how to add the formatting chart options? I ran into an even weirder problem. If I increase the number of worksheets, even the first plot looses it's Left formatting. The above code is the only place where I add formatting so I don't know what is happening. I am sure I am not formatting it correctly.
Many thanks for your suggestions.
Edit: One additional thing which I tested. I am using
WScript.Sleep 500
code before the For loop ends since it gives enough time for earlier operations to finish (at least that's what I understood from many other google searches).
So after some more searching and testing, I found a solution (for my case at least).
Moved the WScript.Sleep 1000 (500 didn't work for me) statement just below CommandBars.ReleaseFocus.
It makes some sense now since it is the Chart copying, pasting and linking from excel that needs time. Especially with source formatting. After that there is only text generation which I believe is not so heavy.
Cleared all the set Object variables when not used. Especially the ones associated with the "With" keyword.
set obj = CreateObject()
With obj
'Do something here.
End With
set obj = Nothing
Not clearing them, apparently, can also prevent you from closing the applications even after you use the .Close and .Quit method. At least that's what I observed. I found PowerPoint.exe running in the task manager when nothing was opened.
After doing the above, I am able to copy with format the charts and also able to set the position of the charts. The weird problem of larger number of worksheets also disappeared. Hopefully, it might help others. If someone thinks the observations are incorrect or troublesome, please correct.

Unexpected results from a Worksheet.Activate event

I’m running excel 2010 on windows 7.
The following macro does what you would expect, ie (1) inserts a new worksheet, (2) adds a rectangle, and (3) activates cell A1.
Sub addSheetAndButton()
Dim buttonSheet As Worksheet
Set buttonSheet = ThisWorkbook.Sheets.Add
buttonSheet.Shapes.AddShape(msoShapeRectangle, 100, 100, 100, 50).Select
buttonSheet.Range("A1").Activate
End Sub
My problem is when I try to run it with a Worksheet.Activate event, for example:
Private Sub Worksheet_Activate()
Call addSheetAndButton
End Sub
This time (1) a new worksheet is not inserted, (2) the rectangle is added to the worksheet associated with the activate event, (3) cell A1 is not activated and (4) the rectangle remains activated.
What am I doing wrong? Any help would be greatly appreciated.
Thanks very much for trying this. I’m sorry it has taken me a while to get back, but I’ve been experimenting with this. I have discovered that when I exit and restart Excel, the addSheetAndButton macro works as expected under the Worksheet.Activate event. However, I have a different macro that uses another Worksheet.Activate event to update some charts. On what seemed to be a random basis, this would create a “run time error 6” - an overflow that resulted from trying to assign an out of bounds value to a variable.
I never got this error if I bypassed the Worksheet.Activate event/macro and ran the chart update macro by hand. After resetting VBA/Excel from the “run time error 6”, the addSheetAndButton macro behaved exactly as I described in my original post. The only way to cure it was to exit and restart Excel.
I think (hope) that I have traced the source of the run time error back to a line in my chart update macro where I had selected rather than activated a worksheet before reading data from it – though I am surprised at the result. It is worth pointing out that once Excel entered the “not as expected” state, the on-screen message from the following two lines was the name of the previous active sheet and not “Sheet1”.
Worksheets(“Sheet1”).Activate
Msgbox ActiveSheet.Name
Again, the only apparent way to cure this was to exit and restart Excel.
Thanks again for your help.

Resources