Question

I've researched for an answer to my problem. I'm a newbie, though I'm picking up really fast.

I want to do something like this:

Sub name()
    Dim waitOne As Date (or Variant?)
    waitOne = Application.Wait(Now + TimeValue("00:00:01"))

    Selection.Copy
        waitOne 'second
    Application.SendKeys "%{Tab}", True 'switching to another application
        waitOne 'second
    Application.SendKeys ("^v"), True
End Sub

Or replace waitOne with the following declaration

 Sub name()

    Function waitSec()
  waitOne = Application.Wait(Now + TimeValue("00:00:01"))
     End Function

    Selection.Copy
        waitSec() 'second
    Application.SendKeys "%{Tab}", True
        waitSec() 'second
    Application.SendKeys ("^v"), True
End Sub

neither of which works. I'm looking to simplfy coding for a cleaner look and easier to read. Thank you in advance for your assistance!

Was it helpful?

Solution

Using Application.Wait to wait for 1 second is highly unreliable as its time resolution is only itself in the order of 1 second. This is in addition to the errors in the syntax of your original code (as you realised).

For short delays, use Sleep from kernel32:

Use it like:

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

Sub mySub()
    Sleep 500 'pauses execution for at least 500 milliseconds
End Sub

So, , use the above for a much simpler and more reliable sleep :)

Edit: just so you realise, you do not define a function inside a sub, you do it outside - like:

Sub mySub()
    MsgBox myFunc()
End Sub
Function myFunc()
    myFunc = "Hello!"
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top