program-5

5. WAP to create a simple calculator (Using control array)

Calculator form Design


Form Description



Source Code:


Option Explicit
Dim Operand1 As Double, Operand2 As Double
Dim Operator As String
Dim ClearDisplay As Boolean

Private Sub ClearBttn_Click()
    Display.Caption = ""
End Sub

Private Sub Digits_Click(Index As Integer)
    If ClearDisplay Then
        Display.Caption = ""
        ClearDisplay = False
    End If
    Display.Caption = Display.Caption + Digits(Index).Caption
End Sub

Private Sub Div_Click()
    Operand1 = Val(Display.Caption)
    Operator = "/"
    Display.Caption = ""
End Sub

Private Sub DotBttn_Click()
    If ClearDisplay Then
        Display.Caption = ""
        ClearDisplay = False
    End If
    If InStr(Display.Caption, ".") Then
        Exit Sub
    Else
        Display.Caption = Display.Caption + "."
    End If
End Sub

Private Sub Equals_Click()
Dim result As Double

On Error GoTo ErrorHandler
    Operand2 = Val(Display.Caption)
    If Operator = "+" Then result = Operand1 + Operand2
    If Operator = "-" Then result = Operand1 - Operand2
    If Operator = "*" Then result = Operand1 * Operand2
    If Operator = "/" And Operand2 <> "0" Then result = Operand1 / Operand2
    Display.Caption = result
    ClearDisplay = True
    Exit Sub
ErrorHandler:
    Dim intMsg As Integer
    intMsg = MsgBox("The operation resulted in the following error" _
    & vbCrLf & Err.Description, vbOKCancel)
   
    Display.Caption = "ERROR " & intMsg
    ClearDisplay = True
End Sub

Private Sub Minus_Click()
    Operand1 = Val(Display.Caption)
    Operator = "-"
    Display.Caption = ""
End Sub

Private Sub Over_Click()
    If Val(Display.Caption) <> 0 Then Display.Caption = 1 / Val(Display.Caption)
End Sub

Private Sub Plus_Click()
    Operand1 = Val(Display.Caption)
    Operator = "+"
    Display.Caption = ""
End Sub

Private Sub PlusMinus_Click()
    Display.Caption = -Val(Display.Caption)
End Sub

Private Sub Times_Click()
    Operand1 = Val(Display.Caption)
    Operator = "*"
    Display.Caption = ""
End Sub