Saranya
Saranya

Reputation: 111

How to call a function (with parameters) which is in function library, taking the function name from a variable?

I'm trying to use getref to call a function from the function library associated with the test. My code -

In action1

str = "sample"
msg = "hi"
x = GetRef("Function_"&str)(msg)
msgbox x

In the function Library,

Function Function_sample(strMsg)
    Function_sample = strMsg
End Function

I'm getting the error -

"Invalid procedure call or argument."

But it works fine if the function is placed in the same action. How to call a function (with parameters) which is in function library, taking the function name from a variable?

Upvotes: 6

Views: 12276

Answers (2)

Pankaj Jaju
Pankaj Jaju

Reputation: 5471

I faced the same issue and found out that associating or loading the functional libraries doesn't work for GetRef. To work around this issue, all you need to do is instead of associating or loading your FL, execute it using ExecuteFile function.

In action1

ExecuteFile "/path/functionallibrary.vbs"
str = "sample"
msg = "hi"
x = GetRef("Function_" & str)(msg)
msgbox x

Upvotes: 2

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38755

Minimalistic working example:

Lib.vbs:

Option Explicit

Function Twice(n)
  Twice = n + n
End Function

Main.vbs:

Option Explicit

Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")

ExecuteGlobal goFS.OpenTextFile(".\lib.vbs").ReadAll()

Dim fpTwice : Set fpTwice = GetRef("Twice")

WScript.Echo fpTwice(42)

Output:

cscript main.vbs
84

The error message "... runtime error: Invalid procedure call or argument: 'GetRef'" indicates that the (importing of the) function library is to blame.

Update:

I think that it is plausible to assume that the VBScript engine keeps a table associating sub/function/method names with callable code to be able to do literal/direct calls:

n = Twice(11)

and that GetRef("Twice") accesses this table. So I would never expect an indirect/'function pointer' call or a GetRef() to fail when the literal invocation succeeds.

But according to this and that, there are at least four ways to 'import' libraries/modules into QTP, and as I don't use QTP I can't rule out, that some (or even all) of these methods do something silly to cause the mis-behaviour you describe.

Upvotes: 5

Related Questions