Charts Do Not Automatically Update When Data Changes

后端 未结 9 2816
庸人自扰
庸人自扰 2021-02-19 18:52

Hopefully this is an easy one. I have a series of charts in MS Excel that point to data on the same worksheet. The data on the worksheet is calculated using a VBA function. W

相关标签:
9条回答
  • 2021-02-19 19:27

    Just figured out the solution to this issue as I was suffering from the same.

    I've just added "DoEvents()" prior to printing or exporting and the chart got refreshed.

    example

    Sub a()
       Dim w As Worksheet
       Dim a
       Set w = Worksheets(1)
    
       For Each a In w.Range("a1:a5")
         a.Value = a.Value + 1
       Next
    
       DoEvents
    
    End Sub  
    
    0 讨论(0)
  • 2021-02-19 19:28

    UDF getWeekValue has to be marked as volatile.

     Function getWeekValue (weekNumber As Integer, valuesRange As Range) As Integer   
     
     Application.Volatile '!!
    
     Dim aCell As Range  
     Dim currentDate As Date
     
     '... 
    
    0 讨论(0)
  • 2021-02-19 19:39

    For example:

    Sub a()
       Dim w As Worksheet
       Dim a
       Set w = Worksheets(1)
    
       For Each a In w.Range("a1:a5")
         a.Value = a.Value + 1
       Next
    
       w.ChartObjects(1).Chart.Refresh
    
    End Sub  
    

    alt text

    0 讨论(0)
  • 2021-02-19 19:42

    Just an idea: in your Worksheet_Change Sub, insert as the first line:

    Application.EnableEvents = False
    

    in order to avoid self-firing events....
    Of course set it back to True at the end of the Sub.

    0 讨论(0)
  • 2021-02-19 19:45

    Running Excel 2019.

    Added the following to the macro code:

    ActiveSheet.ChartObjects(1).Chart.Refresh    
    DoEvents
    

    The chart now updates during macro execution

    0 讨论(0)
  • 2021-02-19 19:46

    It's possible that the issue is the argument list of getWeekValue, which includes only the week number and the data stream.

    If you add a third argument, worksheetDate, then Excel's recalculation engine will be hit on the side of the head with the fact that getWeekValue uses the value held in worksheetDate. In your current implementation, this fact is held only in the VBA code, where it is probably invisible to the recalculation engine.

    I write this so hedgingly because I am not privy to the inner workings of the recalculation engine. (Maybe someone who knows about this better than I can comment on my speculation) But I did do a test, in which getWeekValue does have that third argument, and the chart does recalculate properly. Nice added benefit of this approach: you can remove all that other VBA event management. -HTH

    0 讨论(0)
提交回复
热议问题