首页 > 解决方案 > 将几个组合框值的总和放入单个文本框中

问题描述

一个简单的销售点系统,显示 2 个产品:Apple 和 Banana,每个价格为 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

动图

错误:

错误

标签: excelvba

解决方案


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

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)


推荐阅读