我有一个ListBox,我正在读取有几行的文本文件。我当前正在单击一行来搜索在工作表中单击的值,然后将该值添加到列表框中,该列表框将显示在底部。
如果我的列表框中有10行,我点击第5行,如何将项目添加到第6行?
Sub FindListValue()
Dim FirstAddress As String
Dim rSearch As Range 'range to search
Dim c As Range
Sheets("PN-BINS").Activate
Set rSearch = ActiveSheet.Range("b1", Range("b65536").End(xlUp))
strFind = Me.ListBox1.Value 'what to look for
With rSearch
Set c = .Find(strFind, LookIn:=xlValues, LookAt:=xlWhole)
If Not c Is Nothing Then 'found it
c.Select
'MsgBox strFind & c.Offset(0, -1).Value
Me.ListBox1.AddItem strFind & " " & c.Offset(0, -1).Value
Else: MsgBox strFind & " is not listed!" 'search failed
'Range("K1").Select
End If
End With
End Sub
答案 0 :(得分:1)
实现所需结果需要几个步骤:
MultiSelect
,那么您还可以检查已选择的项目数以及要插入新项目的位置。如果未选择任何内容,则只需将项目添加到列表的末尾。以下是实现上述目标的完整代码:
Option Explicit
Private Sub btnAdd_Click()
Dim y As Long
Dim tmp1 As String
Dim tmp2 As String
Dim curSelection As Long
'If nothing is selected then you can simply add it to the end of the list
If Me.ListBox1.ListIndex < 0 Then
Me.ListBox1.AddItem Me.TextBox1.Value
Exit Sub
End If
'Save the INDEX for the currently selected item
curSelection = Me.ListBox1.ListIndex
tmp2 = Me.TextBox1.Value
For y = curSelection To Me.ListBox1.ListCount - 1
tmp1 = Me.ListBox1.List(y)
Me.ListBox1.List(y) = tmp2
tmp2 = tmp1
Next y
Me.ListBox1.AddItem tmp2
Me.ListBox1.Selected(curSelection) = True
End Sub
这就是最终应该如何运作的方式: