Link to home
Start Free TrialLog in
Avatar of bpl5000
bpl5000

asked on

Calling a function using a variable

I have a string called strFunction.  I want to put one of three values into this string... function1, function2 or function3.  I would like to call the function using the following statement:

strFunction = "function1"
If CallByName(Me, strFunction ("myString"), VbMethod) Then
     'something here
End If

The function would look like this:

Public Function function1(strTest as string) As Boolean
     function1 = True
End Function

This will only work if I don't pass an argument.  In other words, this will work:

If CallByName(Me, strFunction, VbMethod) Then
     'something here
End If

Is there a way to call a function using a variable and pass an argument to the function?
Avatar of Cluskitt
Cluskitt
Flag of Portugal image

It would probably be easier to set up a case statement:
Dim DoStuff As Boolean
Select Case strFunction
  Case "function1"
    DoStuff = function1("MyString")
  Case "function2"
    DoStuff = function2("MyString")
  Case "function3"
    DoStuff = function3("MyString")
  Case Else
    DoStuff = False
End Select
If DoStuff
  'something here
End If
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I would agree with Cluskitt but add one thing...vb can be case sensitive when looking at your variable comparisons...
Make sure you check the casing and the padding of spaces if this is a variable you are getting from a back-end datasource.

dim DoStuff as boolean
dim MyStr as String
MyStr = "MyString" ' whatever right ?
DoStuff = false
Select Case UCase(Trim(strFunction))
   CASE "FUNCTION1"
      DoStuff = Function1(MyStr)
   CASE "FUNCTION2"
      DoStuff = Function2(MyStr)
   CASE "FUNCTION3"
      DoStuff = Function3(MyStr)
End Select
If DoStuff 
   ' yup - it was true :)
End If

Open in new window

Avatar of bpl5000
bpl5000

ASKER

That works awesome... thanks Idle_Mind!