Evaluate a passed string variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mihail
    Contributor
    • Apr 2011
    • 759

    Evaluate a passed string variable

    Hi all !
    I am looking for a way to evaluate string expressions.
    I know about SCRIPT control but this control can't do my job.
    Basically I wish to calculate functions. Something like this:

    Say I have a mathematically function: y = E(x) where E is an expression I don't know at design time. So I need to calculate y by evaluate E at run time. Something like this:

    Code:
    Sub Test
    Dim Y as Double, x As Double, E as String
    
        x = 2
        E = "x + 5"
        Y = Fx(x,E)
        Debug.Print Y 'Should return 7
    
        E = "3*x+4"
        Y = Fx(x,E)
        Debug.Print Y 'Should return 10
    End Sub
    
    Private Function Fx(x As Double, Ex As String)
        Y = Value of Ex ??????
    End Function
    Of course the functions I need to evaluate are more complicated than this so I am looking for a general procedure.

    Can you help me ?
    Thank you !
  • Guido Geurs
    Recognized Expert Contributor
    • Oct 2009
    • 767

    #2
    add the component "ScriptCont rol" to the form.
    This is the code for the calculation:
    Code:
    Private Sub Command1_Click()
       Call Test
    End Sub
    
    Sub Test()
    Dim Y As Double, x As Double, E As String
      
        x = 2
        E = "x + 5"
        Y = Fx(x, E)
        Debug.Print Y 'Should return 7
      
        E = "3*x+4"
        Y = Fx(x, E)
        Debug.Print Y 'Should return 10
    End Sub
      
    Private Function Fx(xval As Double, Ex As String) As Double
    Dim EVALstring  As String
       EVALstring = Replace(Ex, "x", Str(xval))
       Fx = ScriptControl1.Eval(EVALstring)
    End Function

    Comment

    • Mihail
      Contributor
      • Apr 2011
      • 759

      #3
      Thank you Guido !
      I did not know the function "Replace".
      I use a lot of extra code to replace the value of variable in Ex.

      Thank you again.

      Comment

      Working...