2016-11-11 182 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