Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

time delays in VBA

Status
Not open for further replies.

portlandtrailblazer

Technical User
Feb 13, 2005
3
0
0
US
I frequently find that my programs trip over themselves unless I insert a time delay in the code. I insert a time delay by starting a counter to count to 500 or 100 or whatever.

One recent example is getting MSWord to paginate a document. I needed to access BuiltInDocumentProperties for determination of how many pages a document has. It would not work consistently unless I put in a time delay after the document opened.

I have had similar experiences with other functions.
Is this common? Is my approach reasonable?
Thanks
 
I do not use VB(A) that much for automation, so no comment re frequency of occurance.

The technique, however, is a common -and not recommended- soloution. For a (much) more main-stream approach, look at the timer function.





MichaelRed


 
portlandtrailblazer,

Sometimes a time delay may be required but first try using DoEvents after lines of code in which complicated things happen.

Sometimes you can set up a Do loop so that code only continues when the required condition is met. eg. if the preceding code saves a file and the following code reads the file you could

Code to Save the file goes here
Do Until len(dir$(FileName$))
DoEvents
Loop
Code to read the file goes here

In the above example the code will go into an infinite loop if the file cannot be found so it can be made safer as follows;

t& = timer
Do Until len(dir$(FileName$)) or Timer-t >5
Doevents
loop
if len(dir$(FileName$)) then
'Code to read file goes here
else
'could'nt find file after 5 seconds
end if

HTH regards Hugh












 
>try using DoEvents after lines of code in which complicated things happen

See posts passim in this forum (a key word search should do it) as to why I and others tend to advise against using DoEvents wherever possible
 
Hi portlandtrailblazer,

I agree with HughLerwill on trying to use a DoEvents statement. Sometimes it is just a matter of letting the events filter out first before trying to access the data you need.

Additionally you might want to try using the Sleep API method. This will give you a more consistent result on machines that vary in speed/performance. You might get the loop tuned right for a 500Mhz machine but if you try to run it on a 2.4Ghz machine it might not work right, and vice versa. I found this article on MSDN. Hope this helps.

WD97: How to Implement a Delay in Visual Basic for Applications

pozitron
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top