Excel VBA添加下面的列表框select项目

我有一个ListBox,我正在阅读一个文本文件,有几行。 我正在点击一行来search表单中的值,然后将该值添加到列表框的底部。

如果我有我的列表框中有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 

有几个步骤可以达到预期的效果:

  1. 检查列表框上的项目是否被选中。 如果您允许MultiSelect那么您也可以检查已经select了多less项目以及您想要插入新项目的位置。 如果没有select,只需将该项目添加到列表的末尾。
  2. 如果列表中的项目被选中,则存储当前所选项目的INDEX,以便于您
    • 知道在哪里插入新项目和
    • 知道应该在macros的末尾select哪个项目。
  3. 迭代所选项目中的列表框(前面的项目不需要修改)来插入新值并将列表中的“覆盖”值存储在一个临时variables中(这样您可以“覆盖”下一行列表。
  4. 最后,你最后添加一个新的项目到列表中,并将tempvariables作为一个值写入列表(新添加的项目)。

以下是完成上述的完整代码:

 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 

最后这是如何工作的:

在这里输入图像说明