2016-11-11 252 views
1

我有一个列表框,我正在阅读一个文本文件,其中有几行。我现在点击一行来搜索表单中单击的值,然后将该值添加到列表框的底部。Excel VBA添加下列项目列表框选择

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

请发表您的当前VBA代码列表框。 – Ralph

回答

1

有参与达到预期结果的几个步骤:

  1. 如果选择检查列表框的项目。如果您允许MultiSelect,那么您还可以检查已选择了多少项目以及要插入新项目的位置。如果没有选择,只需将该项目添加到列表的末尾。
  2. 如果选择列表中的某个项目,然后存放索引当前选定的项目,以便您
    • 知道在哪里可以插入新项目和
    • 知道哪些项目应在年底选择宏。
  3. 在转发时从选定项目迭代列表框(先前的项目不需要修改)插入新值并将列表中的“覆盖”值存储在临时变量中(这样您可以“覆盖”的下一行列表。
  4. 在最后你终于添加一个新的项目列表,并写入临时变量的值列表(新增项目)。

这里是完成以上代码:

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 

,这是它应该如何在工作进行到底:

enter image description here

+0

这是伟大的....正是我需要的。谢谢 – Noob2Java