View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Sandy[_6_] Sandy[_6_] is offline
external usenet poster
 
Posts: 9
Default Input Box Processing troubles

Works a treat
Thanks
Sandy

"Greg Wilson" wrote in message
...
Sandy,

There are a number of problems. You need to pass the variables to the
outside procedure. You declared them within the first procedure and there
scope is therefore limited to this procedure. You could declare them at
the
top of the module and make them available to all procedures within the
module. However, normally, one would use a function instead of a sub
procedure to "sub out" calculations. You pass the variables directly to
the
function or outside procedure.
You also need to put the operators in quotations (e.g. "add") and take
care
of the circumstance if the user presses Cancel. I suggest using Select
Case
instead of If...Then...ElseIf. Function example:

Private Sub cmdGetNums_Click()
Dim num1 As Single
Dim num2 As Single
Dim doWhat As String
Dim answer As Single
num1 = Val(InputBox("Enter first number.", "First Number"))
num2 = Val(InputBox("Enter second number.", "Second Number"))
doWhat = InputBox("Enter add, subtract, multiply or divide")
MsgBox "The answer is: " & doWithNums(num1, num2, doWhat)
End Sub

Private Function doWithNums(N1 As Single, _
N2 As Single, Op As String) As Single
Select Case Op
Case "Add"
doWithNums = N1 + N2
Case "subtract"
doWithNums = N1 - N2
Case "multiply"
doWithNums = N1 * N2
Case "divide"
doWithNums = N1 / N2
Case Else
doWithNums = 0
End Select
End Function


If you actually intend to use your example in a project then I think it
can
be improved quite a bit. The evaluate method is quite useful in this case:

Private Sub cmdGetNums_Click()
Dim n1 As Single
Dim n2 As Single
Dim Operator As String, txt As String

n1 = Val(InputBox("Enter first number.", "First Number"))
If n1 = 0 Then Exit Sub
n2 = Val(InputBox("Enter second number.", "Second Number"))
If n2 = 0 Then Exit Sub
txt = "Enter the operator for the calculation:" & _
vbCr & """ + "" (to add)" & _
vbCr & """ - "" (to subtract)" & _
vbCr & """ * "" (to multiply)" & _
vbCr & """ / "" (to divide)"
Operator = InputBox(txt, "Operator")
If Operator = "" Then Exit Sub
txt = Application.Evaluate(n1 & Operator & n2)
MsgBox "The answer is: " & txt & vbTab, vbInformation, "Calculation"
End Sub