练习一下控件数组和代码规范性
窗体代码如下
Option Explicit
Dim blnStratrOperationFlag As Boolean '是否开始运算
Dim lngOperationFlag As Long '运算标志
Dim dblFirstOperationValue As Double '先前的操作数
Private Sub cmdValuedDecimal_Click(Index As Integer) '数字及小数点
Select Case Index
Case 0
AddTextOperationValue "0"
Case 1
AddTextOperationValue "1"
Case 2
AddTextOperationValue "2"
Case 3
AddTextOperationValue "3"
Case 4
AddTextOperationValue "4"
Case 5
AddTextOperationValue "5"
Case 6
AddTextOperationValue "6"
Case 7
AddTextOperationValue "7"
Case 8
AddTextOperationValue "8"
Case 9
AddTextOperationValue "9"
Case 10
AddTextOperationValue "."
End Select
End Sub
Private Sub AddTextOperationValue(strOperationValue As String)
If Len(txtOperationValue) > 8 And blnStratrOperationFlag = False Then Exit Sub '判断是否输入数字超过9个
If txtOperationValue = "0" And strOperationValue = "0" Then Exit Sub '是否什么也没输入或为0时候输入0则退出
If lngOperationFlag <> 0 And blnStratrOperationFlag = True Then '如果有操作符且开始运算为真则
txtOperationValue = ""
blnStratrOperationFlag = False
End If
If txtOperationValue = "0" And strOperationValue <> "." Then txtOperationValue = "" '头次输入数字
If Right$(txtOperationValue, 1) = "." And strOperationValue = "." Then Exit Sub '避免多次输入小数点
txtOperationValue = txtOperationValue & strOperationValue '累加字符
End Sub
Private Sub cmdOperation_Click(Index As Integer) '+ - * / =
Select Case Index
Case 0
lngOperationFlag = 1
Evaluate
Case 1
lngOperationFlag = 2
Evaluate
Case 2
lngOperationFlag = 3
Evaluate
Case 3
lngOperationFlag = 4
Evaluate
Case 4
DisposeResult
End Select
End Sub
Private Sub Evaluate() '四则运算赋值
dblFirstOperationValue = Val(txtOperationValue)
blnStratrOperationFlag = True
txtOperationValue = ""
End Sub
Private Sub DisposeResult() '处理计算结果
On Error GoTo ToExit '打开错误陷阱
Select Case lngOperationFlag '操作标志
Case 1
txtOperationValue = dblFirstOperationValue + Val(txtOperationValue)
Case 2
txtOperationValue = dblFirstOperationValue - Val(txtOperationValue)
Case 3
txtOperationValue = dblFirstOperationValue * Val(txtOperationValue)
Case 4
txtOperationValue = dblFirstOperationValue / Val(txtOperationValue)
End Select
lngOperationFlag = 0 '操作标志清0
Exit Sub
ToExit:
MsgBox "除数不能为0!", vbOKOnly, "错误"
Resume Next
End Sub
Private Sub cmdClearAll_Click() 'C按钮清除所有的运算结果
lngOperationFlag = 0
txtOperationValue = "0"
End Sub
Private Sub cmdClearLastInput_Click() 'CE按钮清除最后一次输入的数字
txtOperationValue = "0"
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set frmCalculator = Nothing
End Sub