将多个组合框值的总和放入单个文本框

时间:2019-05-27 08:15:23

标签: excel vba

一个简单的销售点系统,其中显示2种产品:苹果和香蕉,每个价格为10。我需要显示总金额。

我使用了cmbApple_Change()事件 我用if elseif语句

我只能获得1个组合框的结果。

Private Sub cmbApple_Change()

If cmbApple.Value = 0 Then
    txtTotal.Text = 0
ElseIf cmbApple.Value = 1 Then
    txtTotal.Text = 10
ElseIf cmbApple.Value = 2 Then
    txtTotal.Text = 20
ElseIf cmbApple.Value = 3 Then
    txtTotal.Text = 30
End If

End Sub

GIF

错误:

Error

1 个答案:

答案 0 :(得分:0)

这样,您将始终拥有总价值:

Private Sub cmbApple_Change()

    Dim BananaItems As Byte
    Dim AppleItems As Byte

    On Error Resume Next
    AppleItems = cmbApple.Value
    BananaItems = cmbBanana.Value
    On Error GoTo 0

    TxtTotal.Text = AppleItems * 10 + BananaItems * 10

End Sub
Private Sub cmbBanana_Change()

    Dim BananaItems As Byte
    Dim AppleItems As Byte

    On Error Resume Next
    AppleItems = cmbApple.Value
    BananaItems = cmbBanana.Value
    On Error GoTo 0

    TxtTotal.Text = AppleItems * 10 + BananaItems * 10

End Sub
Private Sub UserForm_Initialize()

    Dim i As Byte

    With cmbApple
        For i = 0 To 5
            .AddItem (i)
        Next i
    End With
    With cmbBanana
        For i = 0 To 5
            .AddItem (i)
        Next i
    End With    

End Sub

这很简单,但适用于您的示例。如果您经常需要更改价格,还有其他方法。

编辑:检查已编辑的答案,还更改了代码以添加项目,您可以将For i = 0 to 5更改为所需的任何数字(最大256)