【问题标题】:Inserting single item into ListBox from range将单个项目从范围插入 ListBox
【发布时间】:2014-05-30 17:42:18
【问题描述】:

我有以下从 ListBox1 填充 ListBox2 的代码。这些框是从具有名称标题 (A:AC) 的工作表中填充的,每个名称下方是一个将填充到 ListBox2 中的 Id 列表。每个人可能有多个 ID,或者有些人只有一个。我的2个问题是 1.如何从动态列插入列表框 2. 测试过程中如果有多个ID插入很好但是如果只有一个ID错误。

Private Sub ListBox1_Change()

Dim myArray As Variant
'pulls selected value from listbox1
myArray = ListBox1.List(ListBox1.ListIndex, 0)

Worksheets("Sheet1").Select
Columns("A:CC").Select
'looks for selected value from listbox1
Set found = Cells.Find(What:=myArray, After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False)


If found Is Nothing Then
    'skipper
Else
    found.Offset(1, 0).Select
End If

'below is where i tried to assign the column letter to a variable, didn't work
'Col = Split(ActiveCell(1).Address(1, 0), "$")(0)
'Me.ListBox2.List = Worksheets("Sheet1").Range(Col & "2:" & Col & Range(Col & Range(Col & Rows.Count).End(xlUp).Row).Value

'belwo works great if more than one ID, otherwise it's crap
Me.ListBox2.List = Worksheets("Sheet1").Range("B2:B" & Range("B" & Rows.Count).End(xlUp).Row).Value

End Sub

一些进展。我可以通过动态列查找和填充它,但如果范围只是一个单元格,它仍然无法工作。感谢 avb 提供的代码。

Else
   Set test = Range(found.Offset(1, 0), found.End(xlDown))
test.Copy
End If

Me.ListBox2.List = test.Value

解决方案! 我发现如果只选择了一项,则需要使用 .AddItem 而不是我使用的 .List 。我最终得到了这个最终的 sn-p。

Set sId = Range(found.Offset(1, 0), found.End(xlDown))
    sId.Copy

If IsEmpty(found.Offset(2, 0).Value) Then
   With Worksheets("Sheet1")
      Me.ListBox2.AddItem sId
   End With
Else
   Me.ListBox2.List = sId.Value
End If

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    解决方案!我发现如果只选择了一项,则需要使用 .AddItem 而不是我使用的 .List 。我最终得到了这个最终的 sn-p。

    Set sId = Range(found.Offset(1, 0), found.End(xlDown))
        sId.Copy
    
    If IsEmpty(found.Offset(2, 0).Value) Then
        With Worksheets("Sheet1")
        Me.ListBox2.AddItem sId
    End With
    Else
        Me.ListBox2.List = sId.Value
    End If
    

    【讨论】:

    • +1。 .List 方法需要一个数组。在单单元格范围的情况下,sID(也不是sID.Value)是一个数组。你可以测试If sID.cells.Count > 1 then Me.ListBox2.List = sId.Value: Else: Me.ListBox2.AddItem sID
    • 感谢您清理我发现的内容,就像您的方法一样。
    【解决方案2】:

    假设您的 ID 列表中没有空白单元格,这将起作用:

    Else
        Me.ListBox2.List = Range(found.Offset(1, 0), found.End(xlDown))
    End If
    

    【讨论】:

    • 谢谢,但我收到错误消息无法设置列表属性,无效的属性数组索引
    • 我没有测试就写出来了,因为现在家里没有 Excel,尝试 Range(found.Offset(1, 0), found.End(xlDown)).Select 然后你将查看是否选择了正确的范围。
    • 不幸的是同样的错误。不过谢谢,我会继续努力的。
    • 感谢您的意见 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2010-12-16
    • 2021-11-09
    相关资源
    最近更新 更多