2

I have VBA code to run a particular code and I am trying to pause the next execution by giving it a wait time of 3 seconds using the following line:

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

But I get the following error:

Error: Method or data variable not found

Generic Bot
  • 309
  • 1
  • 4
  • 8
user222213
  • 111
  • 1
  • 2
  • 12

4 Answers4

8

It is best to use External Library references (Early Binding) while developing your code. Early Binding has the advantages of both intellisense and Help documentation. A major disadvantage of Early Binding is that it requires the reference to be updated if a different version of the library is installed. This is way it is best to remove the external references and convert code to Late Binding before distributing it.

Late binding uses CreateObject to import and instantiate a class object.

CreateObject("Excel.Application").Wait (Now + TimeValue("00:00:05"))  

Alternatively, you could reference the WinApi Sleep function.

Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long) 

Usage:

 Sleep 3000 '3000 Milliseconds = 3 second delay
TinMan
  • 6,624
  • 2
  • 10
  • 20
  • 1
    Application.Wait is not the same as Sleep! With Sleep, the application will freeze for that amout of time (usually a very short delay, as otherwise the application seems to be not responding any more), while Wait allows events (like hitting ESC to abort) to be recognized. – Tom Stein Jun 03 '22 at 13:08
  • Good point @TomStein. – TinMan Jun 05 '22 at 05:06
3

I use this function in all of my macros that require a paste operation (sometimes paste is too quick and the pc can't copy the selection in time resulting in an error):

Function Wait(ByVal Seconds As Single)
    Dim CurrentTimer As Variant
    CurrentTimer = Timer
    Do While Timer < CurrentTimer + Seconds
    Loop
End Function

Then apply the following right before any "Selection.Paste" or "Selection.PasteSpecial":

Application.Excel.Wait (Now + TimeValue("00:00:01"))

You may also have to enable the "ExcelPlugInShell 1.0 Type Library" found in Tools > References to get this to function properly as this uses language not available in MS Word by default.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

I tried Excel.Application.Wait(Now + TimeValue("00:00:03")) and it worked like a charm!

Generic Bot
  • 309
  • 1
  • 4
  • 8
user222213
  • 111
  • 1
  • 2
  • 12
0

This works for me:

Set wsh = VBA.CreateObject("WScript.Shell")
   Dim waitOnReturn As Boolean: waitOnReturn = True
   Dim windowStyle As Integer: windowStyle = 0
   Dim errorCode As Integer

   errorCode = wsh.Run("timeout 5", windowStyle, waitOnReturn)

this code allows to run cmd command and wait until execution is finished, in this particular case I am running command "timeout 5" which simly wait 5 seconds. I've found documentation here

Pavlo
  • 1
  • 2