2016-04-10 37 views
0

我得到一個簡單的代碼,如果價值如果lass然後X等待一個小時,否則繼續循環 - 基本上代碼需要運行一個洞一天。VBA代碼運行時使用Excel電子表格

事情是,當代碼在等待線我不能使用excel。 有辦法解決這個問題嗎? 林添加代碼

For i = 1 To 3 
Set OutMail = OutApp.createitem(0) 
LastRefHour = Cells(2, 1).Value 
HourNow = Hour(Now()) 
Set rng = Sheets("Sheet1").Range("D2:G9").SpecialCells(xlCellTypeVisible) 

If (LastRefHour < HourNow) Then 

    ActiveWorkbook.Connections("Monitor-Test").Refresh 
    Application.CalculateUntilAsyncQueriesDone 
    If Not Application.CalculationState = xlDone Then 
    DoEvents 
    End If 

Cells(1, 1).Copy 
Cells(2, 1).PasteSpecial xlPasteValues 

Else: 

    Application.Wait (Now + TimeValue("00:59:00")) 


End If 
+0

請參閱[此答案](http://stackoverflow.com/a/17302474/4088852)。 – Comintern

+0

什麼版本的Excel? –

+0

該版本是優秀的2013年 –

回答

2

的一部分,我會建議使用Timer function (MSDN)

下面是如何使用它:

Option Explicit 

Sub RunCodeInIntervalMode() 
Dim StartTime As Single, FinishTime As Single 
'i decided to set below variable for short interval of time, 
'because this is only an example 
Const WaitTime As Integer = 5 'in second 
Dim i As Integer 'counter 

'clear entire range 
ThisWorkbook.Worksheets(1).Cells.ClearContents 

'define finish time 
FinishTime = Timer + 30 
Do 
    'define start time 
    StartTime = Timer 
    'increase counter 
    i = i + 1 
    'run procedure 
    DisplayTime i, StartTime, FinishTime 
    'enable to work in Worksheet in between next run 
    Do While Timer < StartTime + WaitTime 
     DoEvents 
    Loop 
Loop While Timer < FinishTime 

End Sub 

''let's say below procedure is your procedure 
Sub DisplayTime(ByVal step As Integer, ByVal currTime As Single, ByVal finTime As Single) 

    With ThisWorkbook.Worksheets(1) 
     .Range("A1") = step 
     .Range("B1") = currTime 
     .Range("C1") = finTime 
    End With 
End Sub 

我希望你有一個想法如何做到這一點了。

相關問題