-
I want to do this:
I want my prog to solve calculations (with unknowns (x, y))
Can I do like:
"enter formula in the textbox"
Press a button and then actually get the 'code' excecuted?
I can do
Formula = Text1.Text
but then it's just passed as a string and not 'executed' in any way!?
Thanks!
-
Is this what you're looking for:
Private Sub cmd1_Click()
Dim myResult As Single 'or Double
myResult = Val(Text1.Text * Text2.Text)
Text3.Text = myResult
End Sub
GRAHAM :)
-
I don't believe there is an "automatic" way to do this. You will need to parse the textbox expression to see if its valid, then if so, write the code to carry out the operations specified in the expression.
I'll try to give a simple example. Suppose a vaild expression had to be in this form:
[variable] [operator] [variable]
where the variable had to be x, y, or z and the operator had to be +, -, *, or /. It would be assumed that the values for x, y, and z were established beforehand. (Depending on what expressions you want to support, your parsing routine will be much more complex.)
Code:
Private Sub cmdExecute_Click()
Dim arrTokens() As String
Dim dblVar1 As Double
Dim dblVar2 As Double
Dim dblResult As Double
arrTokens = Split(Trim$(Text1.Text))
If UBound(arrTokens) <> 2 Then GoTo BadExpression
Select Case arrTokens(0)
Case "x" : dblVar1 = x
Case "y" : dblVar1 = y
Case "z" : dblVar1 = z
Case Else
GoTo BadExpression
End Select
Select Case arrTokens(2)
Case "x" : dblVar2 = x
Case "y" : dblVar2 = y
Case "z" : dblVar2 = z
Case Else
GoTo BadExpression
End Select
Select Case arrTokens(1)
Case "+" : dblResult = dblVar1 + dblVar2
Case "-" : dblResult = dblVar1 - dblVar2
Case "* : dblResult = dblVar1 * dblVar2
Case "/" : dblResult = dblVar1 / dblVar2
Case Else
GoTo BadExpression
End Select
' If we make it to this point, we had a valid expression ...
Text2.Text = dblResult
Exit Sub
BadExpression:
MsgBox "Expression not valid", vbexclamation, "Bad Expression"
Text1.SetFocus
End Sub