Excel VBA - 组合框

Excel VBA - Combobox

我有一个带有 2 个组合框(Combobox1 和 Combobox2)以及一个“保存”和一个“取消”按钮的用户窗体。我现在的目标是,每当我 select 一个组合框的一项时,另一项应该被“阻止”或禁用。因此,当按下保存按钮时,它只能保存这两个组合框之一的一项。

这是我的进展:

If ComboBox1.Text = "" Then Cancel = 1 
    MsgBox "Data couldn't be saved. Insert item."
ElseIf Combobox1.Value > 0 And Combobox2.Text = "" Then 
    If Combobox2.Text = "" Then Cancel = 1 MsgBox "Data couldn't be saved. Insert item."
ElseIf Combobox2.Value > 0 And Combobox1.Text = "" Then
    If Combobox1.Value > 0 And Combobox2.Value > 0 Then Cancel = 1 MsgBox "Select only one item."

现在的问题是,当我 select combobox1 的一项和 combobox2 的一项时,它仍然保存它。

在您的用户表单中使用以下内容:

Option Explicit

Private Sub CancelButton_Click()
    'reset boxes
    Me.ComboBox1.Value = vbNullString
    Me.ComboBox2.Value = vbNullString
End Sub

Private Sub ComboBox1_Change()
    ' disable box 2 if box 1 has a value
    Me.ComboBox2.Enabled = (Me.ComboBox1.Value = vbNullString)
End Sub

Private Sub ComboBox2_Change()
    ' disable box 1 if box 2 has a value
    Me.ComboBox1.Enabled = (Me.ComboBox2.Value = vbNullString)
End Sub

Private Sub SaveButton_Click()
    If Me.ComboBox1.Value <> vbNullString Then
        MsgBox "Box 1 has the value"
    ElseIf Me.ComboBox2.Value <> vbNullString Then
        MsgBox "Box 2 has the value"
    Else
        MsgBox "In no box was selected a value"
    End If
End Sub