在ComboBox选择中填充ListBox - “运行时错误' -2147352571(80020005)':类型不匹配”

时间:2017-09-14 01:44:47

标签: excel vba excel-vba listbox

我正在尝试使用与组合框选择匹配的行填充列表框(在A列中)

当我在工作表run-time error '-2147352571 (80020005)':Type mismatch

中找到匹配的记录时,我一直收到此错误

我正在尝试搜索匹配值的范围,然后将A列中每个匹配值的整行添加到列表框中,如果没有,则不执行任何操作。但似乎有匹配,而不是将行复制到列表框,我得到这个错误。

我的理解是,如果没有匹配,""打印,如果有匹配,则ListBox3.AddItem表(" ActionItems")。范​​围(" A2:C8")....组合框从不同的表中获取其列表在工作簿中。

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("A2:C8")
  End If
End Sub

2 个答案:

答案 0 :(得分:0)

ListBox.AddItem Method上写着Item数据类型是String

因此,在链接上的示例中,您可以使用函数将itens添加到结尾或开头:

<强>结束:

Function AddItemToEnd(ctrlListBox As ListBox, _ 
 ByVal strItem As String) 

 ctrlListBox.AddItem Item:=strItem 

End Function

<强>起点。:

Function AddItemToBeginning(ctrlComboBox As ComboBox, _ 
 ByVal strItem As String) 

 ctrlComboBox.AddItem Item:=strItem, Index:=0 

End Function

它只会更改de Index参数

正如@ J.Fox所说,你必须做一个循环来逐个添加它们例如:For each cell in Range("A2:C8"): If cell <> "" Then ListBox3.AddItem cell.Text: Next cell Array < /强>

最好使用退出而不是更改

Private Sub ComboBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
End Sub

答案 1 :(得分:0)

希望这段代码可以完成这项工作。 它有2个部分

1)首先,您找到匹配的所有相关单元格并将它们存储在aray中 2)其次,在列表框中为这些单元格添加相应的行

Private Sub ComboBox3_Change()

' The code below will find all the cells with matching values
' And save them in an array
Dim myrange() As Range, rangestart As Range
k = 0
For i = 1 To 50
        If k = 0 Then
        Set rangestart = Range("A1")
        Else
        Set rangestart = myrange(k).Offset(1)
        End If
    Set Rng = Range(rangestart, Range("A50")).Find(What:=Me.ComboBox3.Value, searchdirection:=xlNext)
    If Not Rng Is Nothing Then
    k = k + 1
    ReDim Preserve myrange(1 To k) As Range
    Set myrange(k) = Rng
    End If
Next i

If k = 0 Then
    MsgBox "No matching item found"
    Exit Sub
End If

' This Code will populate the list box

ListBox3.Clear

For i = 1 To UBound(myrange)
    For j = 1 To 7
        ListBox3.AddItem myrange(i).Offset(, j)
    Next j
Next i



End Sub