2017-06-02 78 views
2

我有一個動態圖表,根據單元格值獲取小時數據的更新。該單元格由滾動按鈕控制或在另一個單元格中手動輸入日期。看看下面的gif來了解一個洞察力;運行宏時更新動態圖表 - 運行Excel中的動畫圖形

我想要做的是更新使用VBA,使它象動畫圖表。下面有這個(僞)代碼;

Option Explicit 

#If VBA7 And Win64 Then 
    '64 bit Excel 
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (_ 
     ByVal dwMilliseconds As Long) 
#Else 
    '32 bit Excel 
    Public Declare Sub Sleep Lib "kernel32" (_ 
     ByVal dwMilliseconds As Long) 
#End If 

Sub Animate() 

On Error GoTo Error ErrorHandler  

Dim wsh As Worksheet 
Dim i As Integer 

Set wsh = ThisWorkbook.Worksheets("AChart") 
Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 

For i = 1 to 3000 
    Sleep 50 
    wsh.Range("K4").Value = i 
    DoEvents 
    Application.Wait Now() + TimeSerial(0, 0, 1) 
Next i 

Exit Sub 
ErrorHandler: 
MsgBox Err.Description & " Procedure Animated Graph" 

End Sub 

這個(特別是DoEvents)不會在屏幕上更新圖表。我想知道是否有辦法實現這一點。

+2

你最好的選擇是'Application.Ontime'。 「睡眠」和其他東西不能很好地工作,因爲VBA仍在運行,所以它會干擾Excel應用程序。嘗試'Ontime'並告訴我們,你知道如何使用它;) –

+1

@ A.S.H它工作。謝謝。 – Masoud

回答

1

Application.OnTime可用於此目的。其他東西,如DoEventsSleep仍將使宏運行並阻止更新圖表(在屏幕上)。

如何製作動態圖形?

首先,完成的緣故,這就是如何使動態圖中的鏈接:

Dynamic Excel Charts

在這裏,你要學會指單元格,使用偏移(或類似的方法)來更改圖表上顯示的數據。

如何自動更改圖表?

下面的代碼是我早期嘗試自動更新圖表數據(所謂的「動畫」)的一種嘗試。 StartFinish是兩張Command Buttons,用戶可以通過它們控制「動態圖」。你可以玩,讓Pause等,根據您的需要,但是這將給有關如何實現這種原始的想法:

Public laststop As Boolean 
Public i As Integer 

Sub start() 
    laststop = True 'This controls schedule in Application.Ontime 

    i = 1 'Reset the date to the first entry each time you press start 
    Call Animate 'calls the main sub 
End Sub 

Sub finish() 
    laststop = False 'Set the schedule to false to stop the macro 
End Sub 

'XXXXXXXXXXXXXXXXXXXX 
'XXX MAIN PROGRAM XXX 
'XXXXXXXXXXXXXXXXXXXX 

Sub Animate() 

On Error GoTo ErrorHandler 

Application.OnTime Now() + TimeSerial(0, 0, 2), "Animate", Schedule:=laststop 

If Not laststop Then GoTo nextline 

Dim wsh As Worksheet 

Set wsh = ThisWorkbook.Worksheets("Dynamic_Graph") 
Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 

wsh.Range("I34").Value = i + 1 
DoEvents 

i = i + 1 

If i > 200 Then laststop = False 'last data entry 


Exit Sub 

ErrorHandler: 

    'Sometimes after running the finish macro these errors are happening that _ 
    'we don't want users to see them as they don't affect the process 

If Err.Description = "The specified dimension is not valid for the current chart type" _ 
Or Err.Description = "Method 'OnTime' of object '_Application' failed" _ 
Then GoTo nextline 

MsgBox Err.Description & " #Procedure: Animated Graph" 

nextline: 
     laststop = False 

End Sub 

感謝@A.S.H的建議OnTime