locked
Sub or Function as an argument to another Sub or Function RRS feed

  • Question

  • How we can pass sub or function as an argument to another sub or function in vbscript. Here function which is getting passed as parameter can also have some other function as a argument.

    Public Sub PrintValue(strValue)
    	Msgbox strValue
    End Sub
    
    Public Function Equals(strVal1, strVal2)
    	IF (strVal1=strVal2) Then
    		Equals = true
    	Else
    		Equals = false
    	End If
    End Function
    
    Public Sub IfElse(cond, trueArg, falseArg)
    	IF cond Then
    		trueArg
    	Else
    		falseArg
    	End If
    End Sub
    
    IfElse ( Equals("a", "ab"), PrintValue("EQUAL"), PrintValue("NOT EQUAL") )

    IfElse ( Equals("a", "ab"), PrintValue("EQUAL"), PrintValue("NOT EQUAL") )

    Tuesday, April 11, 2017 9:28 AM

Answers

  • The problem is that, in VBScript, procedures (Sub or Function) are not data.

    You can work around this somewhat in VBScript using the GetRef function, but this is not an exact equivalent of how it works in JavaScript. You could write your example something like this:


    Sub PrintValue(ByVal Val)
      WScript.Echo Val
    End Sub
    
    Function Equals(ByVal Val1, ByVal Val2)
      Equals = Val1 = Val2
    End Function
    
    Sub IfElse(ByRef Condition, ByRef TrueArg, ByRef TrueArgsParams, ByRef FalseArg, ByRef FalseArgParams)
      If Condition Then
        TrueArg TrueArgsParams
      Else
        FalseArg FalseArgParams
      End If
    End Sub
    
    IfElse GetRef("Equals")("a", "a"), GetRef("PrintValue"), "EQUAL", GetRef("PrintValue"), "NOT EQUAL"
    



    -- Bill Stewart [Bill_Stewart]

    Monday, May 22, 2017 3:25 PM

All replies

  • This is not a VB or VBA forum.

    I recommend that you spend some time with the documentation for whichever system you are using to learn how a program or script is written.


    \_(ツ)_/

    Tuesday, April 11, 2017 10:03 AM
  • The problem is that, in VBScript, procedures (Sub or Function) are not data.

    You can work around this somewhat in VBScript using the GetRef function, but this is not an exact equivalent of how it works in JavaScript. You could write your example something like this:


    Sub PrintValue(ByVal Val)
      WScript.Echo Val
    End Sub
    
    Function Equals(ByVal Val1, ByVal Val2)
      Equals = Val1 = Val2
    End Function
    
    Sub IfElse(ByRef Condition, ByRef TrueArg, ByRef TrueArgsParams, ByRef FalseArg, ByRef FalseArgParams)
      If Condition Then
        TrueArg TrueArgsParams
      Else
        FalseArg FalseArgParams
      End If
    End Sub
    
    IfElse GetRef("Equals")("a", "a"), GetRef("PrintValue"), "EQUAL", GetRef("PrintValue"), "NOT EQUAL"
    



    -- Bill Stewart [Bill_Stewart]

    Monday, May 22, 2017 3:25 PM