Refresh all charts without blinking - vba

The aim is to refresh all charts in Excel after cells recalculation.
I work with Microsoft Excel 2010.
As we know, there is a bug? in Excel so that Excel does not update charts even after
Application.CalculateFullRebuild
A known hack is to do something like this:
Application.ScreenUpdating = False
Temp = ActiveCell.ColumnWidth
ActiveCell.Columns.AutoFit
ActiveCell.ColumnWidth = Temp
Application.ScreenUpdating = True
This does work. However, all Excel charts blink (they become white for a moment while updating). Could you advise, please, is there any way to avoid such blinking?
I tried to call
.Refresh
on all charts (https://msdn.microsoft.com/en-us/library/office/ff198180(v=office.14).aspx):
For Each ChartObject In ActiveSheet.ChartObjects
ChartObject.Refresh
Next
but for some reason my Excel (2010) shows error #438 "Object doesn't support this property or method".
Could you advise, please, do I miss something important?

Untested But the .Refresh may work with this:
Sub ChangeCharts()
Application.ScreenUpdating = False 'This line disable the on screen update for better performance, the blink you see, you could delete both lanes but it will run slower
Dim myChart As ChartObject
For Each myChart In ActiveSheet.ChartObjects
myChart.Chart.Refresh
Next myChart
Application.ScreenUpdating = True'This line reenable the on screen update for better performance, the blink you see, you could delete both lanes but it will run slower
End Sub
And that's because (as the link you provide shows) .Refresh only works with the object Chart and not with the object ChartObjects as you have been trying to apply it. Hope it'll guide you in the right direction. (also added quotes for the blink/flicker on screen in the code)

Happy Pi Day!
I just did some experiments with animating charts, using VBA to change a counter in a cell, and worksheet formulas to recalculate chart data based on this counter.
I used to do a lot of chart animations, back in the days of Excel 97-2003, and those ran pretty well. When Excel 2007 came out, the animations really degraded, and nothing seemed to help. But just now I did these tesst in the latest build of Office 365 (Version 1904, Build 11504). And it turns out, sometime in the past few years or so, Microsoft has made it work better.
Sub ChartAnimation1()
Dim i As Double
For i = 0 To 1000 Step 50
ActiveSheet.Range("Stepper") = i
Next
End Sub
The animation didn't animate, that is, the chart didn't change despite the data changing.
My experience told me I should put something like DoEvents in the code after I change the cell's value.
Sub ChartAnimation2()
Dim i As Double
For i = 0 To 1000 Step 50
ActiveSheet.Range("Stepper") = i
DoEvents
Next
End Sub
This helped a little, the chart changed, but the animation was not smooth. Some steps were missed, and the effect was a herky-jerky animation.
Sub ChartAnimation3()
Dim i As Double
For i = 0 To 1000 Step 50
ActiveSheet.Range("Stepper") = i
DoEvents
DoEvents
Next
End Sub
This ran a bit more slowly than with one DoEvents, but it was a lot smoother; still not perfect, but pretty good.
More than two DoEvents was overkill: the code took the same length of time, and the animation was not any smoother.
I also tried various combinations of Chart.Refresh, Chart.Activate, and ScreenUpdating. Two takeaways:
Without a couple DoEvents, the animation didn't work regardless of what other things I tried.
With a couple DoEvents, none of these extra steps made the animation any smoother, but they could make it significantly slower.
This was pretty interesting, so I'll blog about it some day. When I do I'll come back and post a link.

As is often the case I was sent to this VBA post following a VB.NET query regarding blinking or flashing Excel Charts after turning on Excel ScreenUpdating. Blinking Charts is something that has been driving me mad for a long time now and I have seen no solutions that work including the above solution that looks like it should work but doesn't. I have now found a solution that works 100% for all of my programs. As this is a VBA post I have shown a VBA solution to the flashing charts but my VB.NET solution is for anyone else who is sent to this post looking for a VB.NET solution. My solution is based on the answer by Zegad above but it has a couple of essential additions that are not documented and which to me are not obvious. Use the following sub as a replacement for "MyXLApp.ScreenUpdating = True". If you find it works for you please do not ask me to explain why it works. I'm sure there are many here who could probably explain this but for me it is the result of luck and dogged determination. An odd addition here is that you actually only need to activate and refresh then deactivate any one chart and all of the charts will update without flashing when re-enabled, See 'VB.NET CODE-2 sub below.
Sub ScrUpdateEnableNoFlicker()'VBA CODE
Dim myChartObj As ChartObject
For Each myChartObj In ActiveSheet.ChartObjects
myChartObj.Activate 'IMPORTANT ADDITION
myChartObj.Chart.Refresh
Next
Cells.Range("A1").Select 'IMPORTANT ADDITION
Application.ScreenUpdating = True
End Sub
Private Sub ScrUpdateEnableNoFlicker() 'VB.NET CODE-1
'BEFORE TURNING SCREEN UPDATING BACK ON...
'ACTIVATE and refresh the chart objects on the sheet with the charts.
Dim aSheet As Excel.Worksheet = CType(mXLWrkbk.Sheets("Sheet1"), Excel.Worksheet)
Dim aChartObjects As Excel.ChartObjects = CType(aSheet.ChartObjects, Excel.ChartObjects)
For Each achartobject As Excel.ChartObject In aChartObjects
achartobject.Activate() 'IMPORTANT - Will not work without activating first
Dim achart As Excel.Chart = achartobject.Chart
achart.Refresh()
Next
'Now deactivate the current activated chart object by selecting any cell
'THIS IS IMPORTANT - It will not work without doing this
Dim selRange As Excel.Range = aSheet.Range("A1")
selRange.Select()
'Now turn Screen Updating back on...
'All of the Charts will have updated and will not flicker
mXLApp.ScreenUpdating = True
End Sub
Private Sub ScrUpdateEnableNoFlicker() 'VB.NET CODE-2
'BEFORE TURNING SCREEN UPDATING BACK ON...
'ACTIVATE ANY ONE of the chart objects on the sheet with the charts.
Dim aSheet As Excel.Worksheet = CType(mXLWrkbk.Sheets("Sheet1"), Excel.Worksheet)
Dim aChartObject As Excel.ChartObject = CType(aSheet.ChartObjects("Chart 9"), Excel.ChartObject)
aChartObject.Activate() 'IMPORTANT - Will not work without activating first
'Refresh just the ONE activated chart.
Dim aChart As Excel.Chart = aChartObject.Chart
aChart.Refresh()
'Now deactivate the current activated chart object by selecting any cell
'THIS IS IMPORTANT - It will not work without doing this
Dim selRange As Excel.Range = aSheet.Range("A1")
selRange.Select()
'Now turn Screen Updating back on...
'You only need to activate/deactivate any one chart and all of the Charts will have updated and will not flicker
mXLApp.ScreenUpdating = True
End Sub

I was having this issue when hiding or showing a series in my chart. The change would not be apparent until I would scroll away then back again to the chart, which was really a pain. I tried all the above solutions with no luck until I realized unselecting and selecting again the chart before doing the change would work.
myChart.TopLeftCell.Select
myChart.Select
...
Good luck in your research for a solution ;)

Thanks to those who have posted here before! Without your successes, I would not have smooth animation of a dynamic simulation. In my case, it is an xlXYScatterLinesNoMarkers type chart. Running in VBA.
This works for me when changing the series programmatically. The chart is animated smoothly. Running Excel 2016 64 bit
Public Sub ShowOneAnimationFrame(worksheetName As String, chartName As String, _
xvals() As Double, yvals() As Double)
'update chart series programmatically
'Excel 2016 64bit
'Dec 21, 2020
'Author: S^3
Dim theChart As chart
Dim chrtObj As ChartObject
Dim oneSeries As Series
Set chrtObj = Sheets(worksheetName).ChartObjects(chartName)
Set theChart = chrtObj.chart
If theChart.SeriesCollection.Count = 0 Then
theChart.SeriesCollection.NewSeries
End If
Set oneSeries = theChart.SeriesCollection(1)
'update the series with new values
oneSeries.XValues = xvals
oneSeries.Values = yvals
theChart.Refresh 'required (this and the next line are required but the order doesn't matter)
chrtObj.Select 'required
Cells.Range("A1") = Cells.Range("A1").value 'something like this is required
End Sub

Related

Excel VBA: Animating Visibility of a Range w/ RowHeight loop

I am interested in showing/hiding several ranges on my workbook. Normally I would just test whether or not the range is already hidden and set the following to either true or false rng.EntireRow.Hidden.
I would like to make my project feel more like an app (yes I know excel probably isn't the best place to go with it, but attention to small details like this is my kind of thing). The following is an example of what I am trying to do. It works, especially on a clean worksheet/workbook. The problem is that on the workbook in which I am trying to use it, there is already a ton of data/formatting/shapes on the worksheet. This is causing "skips" in the smoothness of the loop. I have tried different step by's, but nothing really seems to solve it. The DoEvents was necessary in order to see any animation at all.
If anyone has an idea on how to make this work, or if it's at all possible, that would be great. Thanks!
Sub testView()
Dim rng As Range
Dim i As Integer
With ActiveSheet
Set rng = .Range(.Cells(1, 1), .Cells(20, 1))
If rng.EntireRow.Hidden = True Then
For i = 1 To 15 Step 1
rng.EntireRow.RowHeight = i
DoEvents
Next i
Else
For i = 14 To 0 Step -1
rng.EntireRow.RowHeight = i
DoEvents
Next i
End If
End With
End Sub
I do a lot of animations in Excel for pedagogical reasons (mostly animations of charts). I sometimes use variations of the following sub:
Sub Pause(delay As Double)
Dim start As Double
start = Timer
Do While Timer < start + delay
DoEvents
Loop
End Sub
Then in the main code, have something like Pause 0.10 after (or instead of) where you currently have DoEvents. Low tech, but it sometimes helps.

Excel file decided one day to format all of the cells that were General to Custom [$-409]ddd

I've been using this particular file for a number of years (expense tracking/checkbook). It has a few simple macros, but none of them have acted up after several years of fine-tuning to do anything like the effect I've encountered. I'm running Excel 2013, if that makes any difference to the scenario.
Several months ago I noticed that when entering data into an unused area on one of the worksheets, the result shown would be "Mon", "Tue", etc. Looking at the formatting drop-down list in the toolbar showed Custom, instead of General, as I would have expected (the specific formatting is [$-409]ddd). For a long time I just adjusted the formatting on the new work to whatever I needed it to be (General, Accounting, Percentage, etc) and carried on. It's become frustrating recently and I decided to investigate further.
It appears that ALL of the cells that were normally formatted as General, are really formatted as Custom. Most of the cells I didn't notice it on are simply text like Balance, Contribution, etc. so I didn't realize the formatting had changed. Only the cells that I specifically formatted as Accounting, Number, Percentage, etc. remain unaffected by the blanket "Custom-ization".
I don't have any code in my macros that do blanket changes to [$-409]ddd, only one section of code that applies "mmm dd" on one specific page, and it's hard coded to "mmm dd".
Does anyone have any clues on what may have happened? I'm open to suggestions on how to remedy the situation as well. I'm considering just a brute-force macro that walks through all of the cells in all of the worksheets, checks the formatting against [$-409]ddd and changes them to General.
This can happen if the Normal Style has been corrupted. Examine it (using right-click) and fix if necessary:
Gary's Student is most likely right as to the cause of this. Anyway, if you don't know how to fix it that way or the cause turns out to be something else, here is a brute-force way to remedy the situation in all worksheets in the workbook.
Some words of caution:
1) This will take a very long time to run, since it loops through all cells in the workbook.
2) Make sure you insert the name of the wrong number format exactly right, or it won't work.
3) Make a copy of the workbook in question before you try this to make sure you don't break anything unintentionally.
Sub resetNumberFormats()
Dim sht As Excel.Worksheet
Dim cll As Range
Dim wrongNumberformat As String
Application.ScreenUpdating = False
wrongNumberformat = "[$-409]ddd"
For Each sht In Worksheets
For Each cll In sht
If wrongNumberformat = cll.NumberFormat Then cll.NumberFormat = "General"
Next cll
Next sht
Application.ScreenUpdating = True
End Sub
Edit
The following code is much much faster and works in an instant by me. Try this instead:
Sub setNumberFormats()
Dim sht As Excel.Worksheet
Dim cll As Range
Dim wrongNumberformat As String
' insert VBA code for wrong number format below
wrongNumberformat = "[$-409]ddd"
With Application
.FindFormat.NumberFormat = wrongNumberformat
.ScreenUpdating = False
End With
On Error Resume Next
For Each sht In Worksheets
Do While Err.Number = 0
sht.Cells.Find(What:="*", SearchFormat:=True).NumberFormat = "General"
Loop
Err.Clear
Next sht
Application.ScreenUpdating = True
End Sub

Error in script which copies charts from Excel to PowerPoint

I am attempting to call the below Sub in order to copy given chart to a specified PowerPoint presentation. However, when I run the macro which calls this Sub, the line indicated below returns the following error: "Object doesn't support this property or method." What's odd is that both Shapes and Slide do contain the methods which are called. As well, the bitmap is correctly copied to my clipboard and pastes into the slide before the error is called. You will find the Sub() below.
Sub copyChart(chrt As Chart, pres As PowerPoint.Presentation)
Dim curSlide As Slide, dummySlide As Slide
Set dummySlide= pres.Slides(2) 'Second slide is dummy slide.
Set curSlide = dummySlide.Duplicate(1) 'Duplicate dummy, set as current slide.
chrt.CopyPicture Appearance:=xlScreen, Format:=xlBitmap 'Copy the chart as a picture.
curSlide.Shapes.Paste '<-----------Error here.
End Sub
As well, I was hoping to provide a .txt file of my entire script, but was unsure how (it is a little lengthy to paste here). Thanks for your help.
(Note that this implementation is very similar to that at Paste Excel Chart into Powerpoint using VBA, further confusing me.)
I have had a lot of trouble in recent versions of Office. 2003 and earlier didn't have this problem, 2007 and 2010 had it a bit, and 2013 and 2016 have it in spades.
When you step through the code it works fine, but when you run it at full speed, it errors on the paste.
It's as if the copy doesn't have time to finish finish, so when you paste the clipboard doesn't have anything in it yet to paste.
Sometimes this helps:
chrt.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
DoEvents
curSlide.Shapes.Paste
DoEvents tells VBA to wait while background operations have a chance to finish up.
It looks like the error can be attributed to how VBA handles variables across different references. (In particular, how PPT VBA handles them.) I was able to get the macro to work by actively selecting/copying the charts. I will need to do a little more research to get why variables cause problems, but at least I know how tackle the problem.
Sub copyChart(curSlide As Slide)
Dim chr as ChartObject
Set chr = Sheets("CHARTSHEET").ChartObjects(1)
Sheets("CHARTSHEET").Select
ActiveChart.CopyPicture
curSlide.Shapes.PasteSpecial
End Sub
I like to use another method, I like to define an Object, then set it to the pasted Chart. Afterwards, it's much easier modifying the pasted Chart object's parameters inside PowerPoint (from Excel).
See code below:
Sub copyChart(curSlide As Slide)
Dim chr As ChartObject
Dim myChart As Object
Set chr = Sheets("CHARTSHEET").ChartObjects(1)
chr.Copy
' setting myChart object to the pasted chart (let's me later an easy way to modify it's parameters)
Set myChart = curSlide.Shapes.PasteSpecial(ppPasteBitmap, msoFalse) ' can change first parameter to other avaialabe formats : ppPasteGIF, ppPasteEnhancedMetafile, ppPasteOLEObject, etc.
' set different parameters for the pasted chart in PowerPoint slide
With myChart
.Left = 200
.Top = 200
End With
End Sub
In the code line:
Set myChart = curSlide.Shapes.PasteSpecial(ppPasteBitmap, msoFalse)
You can change the first parameter in brackets: ppPasteBitmap to many other avaialble formats (test them and see which one gives you the best result), such as: ppPasteGIF, ppPasteEnhancedMetafile, ppPasteOLEObject, etc.

Making excel graphs appear/disappear

I want a graph only to appear when a condition is fulfilled. To be more precise: I have a drop down menu that changes the content of a graph. If the menu point "Total revenue" is clicked, I want a second graph to appear. I am new to VBA and this is what I came up with so far:
Sub Iffuntion()
Dim SelectedChart As Range
Dim notVisible As Boolean
If Range("D100").Value = Range("E100").Value Then
ActiveSheet.ChartObjects("Testchart").Visible = True
Else
ActiveSheet.ChartObjects("Testchart").Visible = notVisible
End If
End Sub
It works, but I have to execute the VBA to make the graph appear/disappear and I would like that to happen automatically. Also the condition should eventually be in another worksheet to keep the sheet with the graphs nice and tidy. I read that to achieve this I have toI have to activate the other worksheet. Would you recommend this way or is there a better solution?
Thanks for the help and best regards!
Pete
EDIT: Here is the link to a sample file with the proposed solution of Cor_Blimey, that I couldn't get to work properly. The interconnections in the excel are more complicated than they would have to be, but I wanted to be as accurate ad possible in displaying what is actually happening in my excel. Thanks for taking a look!
https://dl.dropboxusercontent.com/u/18406645/sample.xlsm
Assuming you mean that they change, from a data validation drop down list, the contents of a cell then you can put your code into the Worksheet's Worksheet_Change event. This event is fired when the user changes the content of a cell (or by an external link).
Then test for the cell being the right cell then run your code.
Like:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Set rng = Intersect(Target, Me.Range("D100"))
If Not rng Is Nothing Then
If rng.Value = Me.Range("E100").Value Then
Me.ChartObjects("Testchart").Visible = True
Else
Me.ChartObjects("Testchart").Visible = False
End If
End If
End Sub

Chart won't update in Excel (2007)

I have an Excel document (2007) with a chart (Clustered Column) that gets its Data Series from cells containing calculated values
The calculated values never change directly, but only as a result of other cells in the sheet changing
When I change other cells in the sheet, the Data Series cells are recalculated, and show new values - but the Chart based on this Data Series refuses to update automatically
I can get the Chart to update by saving/closing, or toggling one of the settings (such as reversing x/y axis and then putting it back), or by re-selecting the Data Series
Every solution I have found online doesn't work
Yes I have Calculation set to
automatic
Ctrl+Alt+F9 updates everything fine, EXCEPT the chart
I have recreated the chart several times, and on different computers
I have tried VBA scripts like:
Application.Calculate
Application.CalculateFull
Application.CalculateFullRebuild
ActiveWorkbook.RefreshAll
DoEvents
None of these update or refresh the chart
I do notice that if I type over my Data Series, actual numbers instead of calculations, it will update the chart - it's as if Excel doesn't want to recognize changes in the calculations
Has anyone experienced this before or know what I might do to fix the problem?
Thank you
This is the only thing I've found to consistently update a chart. It cuts the root cause of the problem (I assume): the series data is getting cached in the chart. By forcing the chart to re-evaluate the series, we are clearing the cache.
' Force the charts to update
Set sht = ActiveSheet
For Each co In sht.ChartObjects
co.Activate
For Each sc In ActiveChart.SeriesCollection
sc.Select
temp = sc.Formula
sc.Formula = "=SERIES(,,1,1)"
sc.Formula = temp
Next sc
Next co
I have run into this same issue - not sure why, and when it happens the only way I have ever gotten the chart to force update is to change something in the chart definition itself, which can easily be done via VBA as in:
Dim C As ChartObject: Set C = Me.ChartObjects("chart name")
C.Chart.ChartTitle.Text = C.Chart.ChartTitle.Text + "1"
There may be a better answer that gets to the bottom of the problem - but I thought this might help. Working on the sheet I would do a quick Ctrl-X, Ctrl-V on a piece of the chart (or the whole thing) to force the chart to update.
I had this problem while generating 1000+ graphs through VBA. I generated the graphs and assigned a range to their series. However, when the sheet recalculated the graphs wouldn't update as the data ranges changed values.
Solution --> I turned WrapText off before the For...Next Loop that generates the graphs and then turned it on again after the loop.
Workbooks(x).Worksheets(x).Cells.WrapText=False
and after...
Workbooks(x).Worksheets(x).Cells.WrapText=True
This a great solution because it updates 1000+ graphs at once without looping through them all and changing something individually.
Also, I'm not really sure why this works; I suppose when WrapText changes one property of the data range it makes the graph update, although I have no documentation on this.
I had the same problem with a simple pie chart.
None of the macros worked that I tried. Nothing worked on cut, pasting, relocating chart.
The Workaround I found was to edit the chart text, remove the labels, then re-select the labels. Once they re-appeared, they were updated.
This is an absurd bug that is severely hampering my work with Excel.
Based on the work arounds posted I came to the following actions as the simplist way to move forward...
Click on the graph you want update - Select CTRL-X, CTRL-V to cut and paste the graph in place... it will be forced to update.
This works very well for me -- it flips axes on all charts and then flips them back, which causes them to refresh without changing at all.
'Refresh all charts
For Each mysheet In ActiveWorkbook.Sheets
mysheet.Activate
For Each mychart In ActiveSheet.ChartObjects
mychart.Activate
ActiveChart.PlotArea.Select
ActiveChart.PlotBy = xlRows
ActiveChart.PlotBy = xlColumns
ActiveChart.PlotBy = xlRows
Next
Next
This is a known Excel bug...
The best and fastest workaround is the Columns.AutoFit - Trick:
Sub Update_Charts()
Application.ScreenUpdating = False
Temp = ActiveCell.ColumnWidth
ActiveCell.Columns.AutoFit
ActiveCell.ColumnWidth = Temp
Application.ScreenUpdating = True
End Sub
I have another problem of refeshing charts. When generating the charts automatically, some charts appear over and cache the text in the sheet. It happens to be a problem of refreshing the generated charts. When I zoom in or zoom out, I can get the expected results. So I post the solution here if it interest someone.
Programmatically, I added this after generating charts :
ActiveWindow.Zoom = ActiveWindow.Zoom + 1
ActiveWindow.Zoom = ActiveWindow.Zoom - 1
Ok I have a solution, really....
I found that the problem with my charts not updating first occurred shortly after I had hidden some data columns feeding the chart, and checked "show data hidden in rows and columns" in the Chart's "Select Data Source" msg box).
I found that if I went back into the "Select Data Source" msg box and unchecked/rechecked the "show data hidden in rows and columns" that the chart refreshes.
Programatically I inserted the following into a Macro that I linked a button to, it refreshes all of my charts quick enough for a workaround to a known bug. This code assumes one chart per worksheet but another for statement for charts 1 to N could be added if desired:
Sub RefreshCharts()
Application.ScreenUpdating = False
For I = 1 To ActiveWorkbook.Worksheets.Count
Worksheets(I).Activate
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.PlotVisibleOnly = True
ActiveChart.PlotVisibleOnly = False
Next I
Application.ScreenUpdating = True
End Sub
I faced the same issue. The issue is due to restriction in no. of calculated formulas in your sheet. you can solved it using two ways:
Manual force re-calculate:
Press SHEFT + F9
Macro to force re-calculate:
add below code to the end of the function which changes the data
Activesheet.Calculate
I found the solution of it:
From excel options make sure to change the calculation options as below. It changed sometimes to manual after heavy work in excel.
We found a solution that doesn't involve VBA: multiplying some element of the chart's data range by TODAY()-TODAY()+1.
Even though the range was recalculating without this, the volatile nature of TODAY() somehow gives it an extra boost that triggers the chart recalc.
This problem is ridiculous! No one's solution worked for me in 2010, but I based mine off of tpascale's:
Dim C As ChartObject
Set C = ActiveSheet.ChartObjects("CTR_Chart")
C.Chart.SetSourceData Source:=Range( _
"KeywordBreakdown!$A$8:$A$12,KeywordBreakdown!$E$8:$E$12")
Simply redefined the Source Data range. If it's a named range, that could conceivably be reasonably clean. I guess the best solution to this is keep trying to modify different chart properties until it refreshes.
I had this problem and found that it was caused by having two excel applications running at the same time. If I closed everything and opened just the file I was having problems with the charts where dynamic like they should be. Maybe this helps
This worked for me, it cuts and re-pastes the charts on the active worksheet. I based this off of Jason's code and a blog post I found in a quick Google search.
Sub RepasteCharts()
Dim StrTemp As String
Dim IntTempTop As Integer
Dim IntTempLeft As Integer
Set sht = ActiveSheet
For Each co In sht.ChartObjects
'Activate the chart
co.Activate
'Grab current position on worksheet
IntTempTop = ActiveChart.Parent.Top
IntTempLeft = ActiveChart.Parent.Left
'Cut and paste
ActiveChart.Parent.Cut
ActiveSheet.Paste
'Reposition to original position
ActiveChart.Parent.Top = IntTempTop
ActiveChart.Parent.Left = IntTempLeft
Next co
End Sub
From Excel 2013 on, there is the Chart.Refreh method (https://msdn.microsoft.com/de-de/library/office/ff198180.aspx) which worked for me:
Dim cht As ChartObject
For Each cht In ThisWorkbook.ActiveSheet.ChartObjects
cht.Chart.Refresh
Next cht
Just spent half a day on this myself.
I have a macro that changes values that are the data for a chart. All worked fine in Excel 2003, but in Excel 2007 the chart seems to lose all connection to its data, although manually changing data values in two column triggered a recalc.
My solution has been to make all charts on the active sheet invisible before the change in data, then make them visible again and call chart refresh for good measure. ( It only seems to be visible charts that have this problem updating ).
This works for me and also handles similar issues with charts as well as chart objects. The refresh may not be necessary - more testing needed.
Dim chrt As Chart
Dim chrtVis As XlSheetVisibility
Dim sht As Worksheet
Dim bChartVisible() As Boolean
Dim iCount As Long
Dim co As ChartObject
On Error Resume Next
Set chrt = ActiveChart
If Not chrt Is Nothing Then
chrtVis = chrt.Visible
chrt.Visible = xlSheetHidden
End If
Set sht = ActiveSheet
If Not sht Is Nothing Then
ReDim bChartVisible(1 To sht.ChartObjects.Count) As Boolean
iCount = 1
For Each co In sht.ChartObjects
bChartVisible(iCount) = co.Visible
co.Visible = False
iCount = iCount + 1
Next co
End If
DO MACRO STUFF THAT CHANGES DATA
If Not sht Is Nothing Then
iCount = 1
For Each co In sht.ChartObjects
co.Visible = bChartVisible(iCount)
co.Chart.Refresh
iCount = iCount + 1
Next co
End If
If Not chrt Is Nothing Then
chrt.Visible = chrtVis
chrt.Refresh
If chrt.Visible Then
chrt.Select
End If
End If
On Error GoTo 0
I had the same issue as the poster. Basically I'm running a dashboard, and I have a bunch of named ranges that are populated with return values from some UDFs. On the dashboard, there are some pie charts with data series tied to cells which contain these named ranges (the problem also occurs if the data series target cells contain the UDFs directly, bypassing the named ranges).
I change a cell value which contains, for example, the date range to base the dashboard on, and the named ranges and UDFs are forced to calculate. However, the pie charts do not update--for some reason, other types of charts do. And by the way, these are chart objects, not chart sheets. Anyway, let's cut to the solution:
I didn't want to visibly change the chart title or some other aspect of it, and anyway I noticed this wasn't updating my charts consistently. Sometimes the first time I triggered the calculation the pies would update, but with subsequent calculations the pies would not. I did notice, however, that every time I made a change in the code my dashboard worked. Thus:
Solution:
With ActiveWorkbook.VBProject.VBComponents("ThisWorkbook").CodeModule
.AddFromString "'test"
.DeleteLines 1
End With
If you're using the Workbook module (I wasn't in this case), just create a new module and reference that instead.
I faced the same problem with my work last week when I added some more calculation to my sheet. After that, using radio buttons to select data to be presented on graphs did not update the graphs anymore.
The best explanation I have been able to find so far is this:
http://support.microsoft.com/kb/243495
If I understood it right, if there are more than 65536 formulas that have another cell as a reference in your file, Excel starts to optimize the calculation and in some cases graphs don't update correctly anymore.
If there is a workaround for this without using VBA macros, I would be glad to hear that (can't use those as the files need to be shared through SharePoint without VBA macros).
What worked for me was using a macro to insert/remove a column in the data table for the chart. This will cause the chart to update the data selection.
I found this to be the fastest way to fix it.
I had the same problem while working through a tutorial (very frustrating when you follow the steps and don't get the expected result).
The tutorial to create a pie chart wanted me to select range A3:A10, then also select non-adjacent range E3:E10. I did so. I got the chart.
It then asked me to change a value and watch the percentage change, then to look at the pie chart and see the update.
It didn't update.
I looked at the data source for the pie chart, and the range was bizarre. It had the A3:A10 range notated properly, but the E10 cell reference repeated several times, and it had all of the E cells listed in a random order. It looked like
=SERIES(,(Revenue!$A$3:$A$10,Revenue!$E$3,Revenue!$E$10,Revenue!$E$10,Revenue!$E$10,Revenue!$E$10,Revenue!$E$10,Revenue!$E$9,Revenue!$E$8,Revenue!$E$7,Revenue!$E$6,Revenue!$E$5,Revenue!$E$4),1
I changed the data source to read:
=SERIES(,Revenue!$A$3:$A$10,Revenue!$E$3:$E$10,1)
Problem solved. Sometimes it's a matter of cleaning up your code so the calculations processor has less to sort through.
I struggled with this problem, too. Finally solved it by recalculating the sheet that has the chart data AFTER the custom function has recalculated. So, in Sheet 1, I have a cell that contains
=ComputeScore()
In the VBA module, the function is defined as Volatile, to ensure that ComputeScore() runs after any updates to the spreadsheet.
Function ComputeScore() As Double
Application.Volatile True
. . . do some stuff to get a total . . .
ComputeScore = theTotal
End Function
Then, in the VBA of Sheet 1, this:
Private Sub Worksheet_Calculate()
'Recalculate the charts data page to force the charts to update.
'Otherwise, they don't update until the next change to a sheet, and so
'chart data is always one update behind the user's data changes.
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlManual
Sheets("Charts Data").Calculate
Application.Calculation = xlAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
So, the sheet named Charts Data, which references the custom function cell of Sheet 1, will do a recalculation AFTER the ComputeScore() function has updated the cell of Sheet 1, since Worksheet_Calculate() fires after the ComputeScore() recalc. This additional round of calculation of the chart data causes the chart to update now, rather than later or not at all. The setting of EnableEvents and xlManual keeps infinite recalc loops and other event problems from occurring.
This might look extremely basic but I just tried Manual Calculating on the spreadsheet where the charts were (by pressing F9) and it worked! Tha VBA code for it is simply:
Calculate
;)
As i tried pretty much ALL the presented solutions and since none worked in my case, I'll add my two cents here as well. Hopefully it helps someone else.
The consensus on this issue seems to be that we need to somehow force excel to redraw the graph since it is not doing it when it should.
My solution was to kill the X-Axis data and replace it with nothing, before changing it to what i wanted. Here my code:
With wsReport
.Activate
.ChartObjects(1).Activate
ActiveChart.FullSeriesCollection(1).XValues = "=" 'Kill data here
.Range("A1").Select 'Forwhatever reason a Select statement was needed
.ChartObjects(1).Activate
ActiveChart.FullSeriesCollection(1).XValues = "=tblRef[Secs]"
End With
End Sub
My two cents for this problem--I was having a similar issue with a chart on an Access 2010 report. I was dynamically building a querydef, setting that as the rowsource on my report and then trying to loop through each series and set the properties of each series. What I eventually had to do was to break out the querydef creation and the property setting into separate subs. Additionally, I put a
SendKeys ("{DOWN}")
SendKeys ("{UP}")
at the bottom of each of the two subs.
On changing the values of the source data, chart was not getting updated accordingly. Just closed all instances of excel and restarted, problem disappeared.
I had a similar problem - Charts didn't appear to update. I tried just about everything on this thread with no luck. I finally realized that the charts that I was copying and pasting were linked to the source data, and that is why they were all showing the same results.
Be sure you are copying and pasting pictures before you go through all the other motions....
I just had the same problem, and also found that the line would only display if I put in bad data (characters instead of numbers). This caused the line to appear, but changing back to valid data caused it to disappear again.
What I found is that if I double-clicked the line (appearing with bad data), it showed me that it was on the SECONDARY axis for some reason. Changing that to PRIMARY axis solved my problem.
I was having a similar problem today with a 2010 file with a large number of formulas and several database connections. The chart axis that were not updating references ranges with hidden columns, similar to others in this chain, and the labels displayed the month and year "MMM-YY" of the dynamic data. I tried all solutions listed except for the VBA options as I'd prefer to solve without code.
I was able to solve the issues by encapsulating my dates (the axis labels) in a TEXT formula as such: =TEXT(A10,"MMM-YY"). And everything immediately updates when values change. Happy days again!!!
From reading the other contributors issues above I started to think that the Charts were having problems with the DATE data type specifically, and therefore converting the values to text with the TEXT function resolved my issue. Hopefully this may help you as well. Just change the format within the double quotes (second argument of the TEXT function) to suit your needs.
Just activate the sheet where the chart is:
Sheets(1).Activate
and your problem disappears.
I had the same problem and none of the things you mentioned in question worked for me until I just activated sheet. The accepted answer didn't work for me neither.
Alternatively you can make:
ActiveCell.Activate
For me the macro didn't update the x-axis for all series, but only the first one. The solution I found was to update the x-axis for all series and then it refrehsed (also I had code to change the format of the x-axis, but I don't think that that was the problem).
ActiveSheet.ChartObjects("Diagram 7").Activate
ActiveChart.Axes(xlCategory).Select
ActiveChart.SeriesCollection(1).XValues = "={""""}"
ActiveChart.SeriesCollection(1).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(2).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(3).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(4).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(5).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(6).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(7).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(8).XValues = "=YYY!$BQ$85:$BQ$8844"
Full macro;
Sub TEST()
'
' TEST Makro
'
ActiveSheet.ChartObjects("Diagram 7").Activate
ActiveChart.Axes(xlCategory).Select
Selection.TickLabels.NumberFormat = "#"
ActiveSheet.ChartObjects("Diagram 7").Activate
ActiveChart.SeriesCollection(1).XValues = "={""""}"
ActiveChart.SeriesCollection(1).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(2).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(3).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(4).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(5).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(6).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(7).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.SeriesCollection(8).XValues = "=YYY!$BQ$85:$BQ$8844"
ActiveChart.Axes(xlCategory).Select
ActiveChart.Axes(xlCategory).TickMarkSpacing = 730
ActiveChart.Axes(xlCategory).TickLabelSpacing = 730
End Sub