Multiple Variable Arguments to Application.OnTime

我怕爱的太早我们不能终老 提交于 2019-11-28 12:27:04

you have to consider the following constraints:

  • the macro you want to call has to reside in a module. When you want to call it from another workbook it has to be public.
  • you cannot use brackets for calling the macro like you would do with a function or a sub with parameters most probably. When using brackets Excel will complain that macro doesn't exist
  • I didn't try a function, but anyway there is nobody who can work with the return value, so define your method as a sub.
  • you have to use aposthophs to encapsulate the macro name
  • you have to use quotes to encapsulate string and date values , either with chr$(34) (reminds me to old times) or just double the quotes
  • you can pass over integers without quotes, I didn't try Doubles
  • separate arguments by a comma
  • the order of the arguments must match the order of the arguments in your method

Find attached the code:

Option Explicit

Sub Test()
    Dim strTest1 As String
    Dim strTest2 As String

    strTest1 = "This is test1"
    strTest2 = "This is test2"

    Application.OnTime Now + TimeSerial(0, 0, 1), "'CallMeOnTime """ & strTest1 & """,""" & strTest2 & "'"
    Application.OnTime Now + TimeSerial(0, 0, 1), "'CallMeOnTime " & Chr$(34) & "Test" & Chr$(34) & "," & Chr$(34) & "Test" & Chr$(34) & "'"
    Application.OnTime Now + TimeSerial(0, 0, 1), "'CallMeOnTime2'"
End Sub
Public Sub CallMeOnTime(strTest1 As String, strTest2 As String)
    MsgBox ("test1: " & strTest1 & " test2:" & strTest2)
End Sub

Public Sub CallMeOnTime2()
    MsgBox ("CallMeOnTime2")
End Sub

Just wanted to add an additional example which I found helpful, with reference to this post on MrExcel.

Application.OnTime with multiple arguments of different types (String and Integer)

Dim testName As String
Dim counter As Integer

...

' String then Integer argument
Application.OnTime Now + TimeValue("00:00:02"), "'TestSub """ & testName & """, " & counter & " '"

' Integer then String argument
Application.OnTime Now + TimeValue("00:00:02"), "'SubTest " & counter & ", """ & testName & """ '"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!