由于动态组合框,清除 userform sub 给出 1004 错误

Clear userform sub giving 1004 error due to dynamic combobox

我正在处理客户投诉数据库。我想为数据输入实现一个用户表单。

我有一个清除用户表单的按钮。它清除 ComboBox2 的整个表单 except,其结果取决于 ComboBox1 的选择。

我收到 1004 运行 次错误,该错误会回调我用于 ComboBox2 的 Match 函数。

Private Sub CommandButton2_Click()
    Clear_Form
End Sub
Sub Clear_Form()
    Me.ComboBox2.Clear
    For Each ctl In Me.Controls
        Select Case TypeName(ctl)
            Case "TextBox"
                ctl.Text = ""
            Case "ComboBox"
                ctl.ListIndex = -1

        End Select
    Next ctl
End Sub
Private Sub UserForm_Activate()
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Customer")

    Dim i As Integer
    Me.ComboBox1.Clear
    For i = 1 To Application.WorksheetFunction.CountA(sh.Range("1:1"))
        Me.ComboBox1.AddItem sh.Cells(1, i).Value

    Next i
End Sub
Private Sub ComboBox1_Change()
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Customer")
    Dim i As Integer
    Dim n As Integer

    n = Application.WorksheetFunction.Match(Me.ComboBox1.Value, sh.Range("1:1"), 0)
    Me.ComboBox2.Clear
    For i = 2 To Application.WorksheetFunction.CountA(sh.Cells(1, n).EntireColumn)
        Me.ComboBox2.AddItem sh.Cells(i, n).Value
    Next i
End Sub

你会得到一个错误,因为 Clear_Form 清除组合框,组合框又调用 _Change 事件,而 Match 失败,因为组合框中没有值。只需在 _Change 事件中添加一行。

Private Sub ComboBox1_Change()
    If ComboBox1.ListIndex = -1 Then Exit Sub '<~~ ADD THIS

    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Customer")
    Dim i As Integer
    Dim n As Integer

    n = Application.WorksheetFunction.Match(Me.ComboBox1.Value, sh.Range("1:1"), 0)

    Me.ComboBox2.Clear

    For i = 2 To Application.WorksheetFunction.CountA(sh.Cells(1, n).EntireColumn)
        Me.ComboBox2.AddItem sh.Cells(i, n).Value
    Next i
End Sub