我正在尝试使用与组合框选择匹配的行填充列表框(在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
答案 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