我正在为我的工作处理客户投诉数据库,我想实现一个用户表单,以使办公室工作人员更容易输入数据。我刚刚开始使用它,但是我已经遇到一个错误,无法弄清楚该如何解决或解决。
我有一个按钮可以清除用户表单。但是,当我单击按钮时,它将清除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
答案 0 :(得分:1)
您将收到错误消息,因为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