Sub Test_MWE_Str2Num()
Dim IRC As Single
Dim X As Single
Dim strBuffer As String
GetNum:
strBuffer = InputBox("enter value for X (enter end to quit)")
If LCase(strBuffer) = "end" Then Exit Sub
Call MWE_Str2Num(strBuffer, X, IRC)
MsgBox "original text: " + strBuffer + Chr(10) + _
"return code: " + Str(IRC) + Chr(10) + _
"numerical value: " + Str(X), vbInformation
GoTo GetNum
End Sub
Sub MWE_Str2Num(strValue As String, X, IRC)
' Title MWE_Str2Num
' Target Application: any supporting VB / VBA
' Function decodes a text string into its numeric equivalent; able to
' decode basic numerics, e.g., 123 , 123.456 , 1.25E3 , 1.25E-2, etc
' plus any combination of basic numbers and simple math operators,
' for example:
' 7/8 1.2/3.4
' 1+7/8 1.25 + 3/4
' 2+3
' 1/2 + 3/4
' 4.21*5.17
'
' Parentheses are allowed but are NOT interpreted as mathematical
' constructions, rather, they are simply ignored
' Limitations: Practically limited to simple expressions. Math operator
' sequence is +, -, *, /, \ left to right
' Processing is recursive, so any combination of numbers and
' operators can be accomodated, but results may be incorrect
' because of the math operation sequence.
' Passed Values
' strValue [input, string] text string
' X [returned, single] numeric value
' IRC [returned, integer] return code (0 = bad; 1 = OK)
' Public/Private Variables used: None
' MATools/MWETools Subroutines Called:
' MWE_Str2Num (recursively)
' VBA procedures called:
' IsNumeric
' Len
' Mid
' Replace
' External Files Accessed: NONE
' Orig Date 17-Mar-2005
' Orig Author MErdrich
' HISTORY
Dim I As Integer, IRC1 As Integer, IRC2 As Integer, Locn As Integer
Dim X1 As Single, X2 As Single
Dim MathOp(5) As String
MathOp(1) = "+"
MathOp(2) = "-"
MathOp(3) = "*"
MathOp(4) = "/"
MathOp(5) = "\"
' remove parentheses
strValue = Replace(strValue, ")", "")
strValue = Replace(strValue, "(", "")
' start with simpliest case of normal numeric
If IsNumeric(strValue) = True Then
X = strValue
IRC = 1
Exit Sub
End If
' not simple numeric; recursively process For I = 1 To 5
Locn = InStr(1, strValue, MathOp(I))
If Locn > 0 Then
Call MWE_Str2Num(Mid(strValue, 1, Locn - 1), X1, IRC1)
Call MWE_Str2Num(Mid(strValue, Locn + 1, Len(strValue) - Locn), X2, IRC2)
If IRC1 * IRC2 <> 1 Then GoTo NotNumeric
Select Case MathOp(I)
Case "+"
X = X1 + X2
Case "-"
X = X1 - X2
Case "*"
X = X1 * X2
Case "/"
X = X1 / X2
Case "\"
X = X1 \ X2
End Select
IRC = 1
Exit Sub
End If
Next I
' not numeric !
NotNumeric:
IRC = 0
End Sub