gpt4 book ai didi

excel - 将单个项目从范围插入 ListBox

转载 作者:行者123 更新时间:2023-12-04 21:38:56 25 4
gpt4 key购买 nike

我有以下来自 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 。我最终得到了这个最后的片段。
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

最佳答案

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

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 - 将单个项目从范围插入 ListBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23960493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com