Monday, September 28, 2015

Simple calculator

This is a simple calculator. You enter numbers to calculate, then you can choose a operator for the calculation as follows:

To make the UserFom with Excel VBA, you must make a interface as follows:
The box at the top is TextBox1. The box at the second top is TextBox2. The box at the bottom is TextBox3. Others are a combo-box and a button.

The code is below:
------------------------------------------------------------------------------
Dim NumResult As Double

Private Sub TextBox1_Change()

If IsNumeric(TextBox1.Value) = False Then
TextBox1.Value = ""
End If

End Sub

Private Sub TextBox2_Change()

If IsNumeric(TextBox2.Value) = False Then
TextBox1.Value = ""
End If

End Sub

Private Sub UserForm_Initialize()
TextBox1.SetFocus
TextBox2.SetFocus


ComboBox1.AddItem "+"
ComboBox1.AddItem "-"
ComboBox1.AddItem "/"
ComboBox1.AddItem "multiply"
 
TextBox3.Value = NumResult

End Sub
Private Sub CommandButton1_Click()
Dim Num1 As Double
Dim Num2 As Double

Num1 = TextBox1.Value
Num2 = TextBox2.Value

If ComboBox1.Value = "+" Then
        NumResult = Num1 + Num2
        TextBox3.Value = NumResult
ElseIf ComboBox1.Value = "-" Then
    NumResult = Num1 - Num2
    TextBox3.Value = NumResult
ElseIf ComboBox1.Value = "/" Then
    TextBox3.Value = (Num1 / Num2)
ElseIf ComboBox1.Value = "multiply" Then
    NumResult = Num1 * Num2
    TextBox3.Value = NumResult
End If


End Sub