【发布时间】: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
【问题讨论】: