我正在尝试用与组合框选择相匹配的行填充列表框(在 A 列中)
当我找到工作表中有匹配项的记录时,我总是收到此错误run-time error '-2147352571 (80020005)':Type mismatch
我尝试在范围内搜索匹配值,然后将它们添加到列表框中,如果没有,则不执行任何操作。但似乎当有匹配项时,我会收到此错误,VBA 不是我的菜,有点困惑。请帮忙。
Private Sub ComboBox3_Change()
Set Rng = Sheets("ActionItems").Range("A2:A50").Find(what:=Me.ComboBox3.Value)
If Rng Is Nothing Then
ListBox3.Value = ""
Else
ListBox3.AddItem Sheets("ActionItems").Range("B2:C8")
End If
End Sub
答案1
ListBox3.AddItem
:
- 对于单列列表框,向列表添加一个项目(一个单元格)
- 对于多列列表框,向列表添加一行
因此您无法添加多个单元格Range("B2:C8")
有 2 个选项:
使用.ListFillRange
接受字符串(范围的地址)
Private Sub ComboBox3_Change()
Dim rng As Range
With Sheets("ActionItems")
Set rng = .Range("A2:A5").Find(What:=Me.ComboBox3.Value)
ListBox3.ListFillRange = IIf(rng Is Nothing, vbNullString, .Range("B2:C8").Address)
End With
End Sub
或者:
Private Sub ComboBox3_Change()
Dim rng As Range, itm As Variant, i As Long
With Sheets("ActionItems")
Set rng = .Range("A2:A5").Find(What:=Me.ComboBox3.Value)
'ListBox3.Clear 'This depends on how you populated the listbox
ListBox3.ListFillRange = vbNullString
If Not rng Is Nothing Then
For Each itm In .Range("B2:C8")
ListBox3.AddItem itm
Next
End If
End With
End Sub
答案2
谢谢 Paul,不过从那以后我改变了方向。我无法让组合框按我想要的方式工作。我后来将其更改为文本框,如下所示。我想做的是允许用户在文本框中键入内容,并让列表框显示任何匹配的结果(如果有)。我拥有的新代码将找到单个结果并突出显示它,但我无法让列表框过滤可见结果,不知道该怎么做。
Private Sub TextBox3_Change()
'searches ListBox3 for match and hightlights result. Need to filter results.
Dim i As Long
Dim sFind As String
sFind = Me.TextBox3.Text
If Len(sFind) = 0 Then
Me.ListBox3.ListIndex = -1
Me.ListBox3.TopIndex = 0
Else
For i = 0 To Me.ListBox3.ListCount - 1
If UCase(Left(Me.ListBox3.List(i), Len(sFind))) = UCase(sFind) Then
Me.ListBox3.TopIndex = i
Me.ListBox3.ListIndex = i
Exit For
End If
Next i
End If
End Sub