在listbox vba中找到所选项的行#

时间:2014-04-14 01:36:28

标签: excel vba excel-vba listbox

如何在列表框中找到所选项目的行数?

现在我有sub将所有找到的项目输入到列表框中,见下文

Sub findnext()
Dim Name As String
Dim f As Range
Dim ws As Worksheet
Dim s As Integer
Dim findnext As Range

Set ws = ThisWorkbook.Worksheets("Master")
Name = surname.Value
ListBox1.Clear
Set f = Range("A:A").Find(what:=Name, LookIn:=xlValues)
Set findnext = f

Do
 Debug.Print findnext.Address
 Set findnext = Range("A:A").findnext(findnext)

 ListBox1.AddItem findnext.Value
 ListBox1.List(ListBox1.ListCount - 1, 1) = ws.Cells(findnext.Row, xFirstName).Value
 ListBox1.List(ListBox1.ListCount - 1, 2) = ws.Cells(findnext.Row, xTitle).Value
 ListBox1.List(ListBox1.ListCount - 1, 3) = ws.Cells(findnext.Row, xProgramAreas).Value
 ListBox1.List(ListBox1.ListCount - 1, 4) = ws.Cells(findnext.Row, xEmail).Value
 ListBox1.List(ListBox1.ListCount - 1, 5) = ws.Cells(findnext.Row, xStakeholder).Value
 ListBox1.List(ListBox1.ListCount - 1, 6) = ws.Cells(findnext.Row, xofficephone).Value
 ListBox1.List(ListBox1.ListCount - 1, 7) = ws.Cells(findnext.Row, xcellphone).Value
'ListBox1.List(ListBox1.ListCount - 1, 8) = ws.Cells(findnext.Row, xFirstName).Value
Loop While findnext.Address <> f.Address

End Sub

如果用户选择了列表框中的项目,那么它会将信息填充到用户表单的文本框中

Sub ListBox1_Click()

    surname.Value = ListBox1.List(ListBox1.ListIndex, 0)
    firstname.Value = ListBox1.List(ListBox1.ListIndex, 1)
    tod.Value = ListBox1.List(ListBox1.ListIndex, 2)
    program.Value = ListBox1.List(ListBox1.ListIndex, 3)
    email.Value = ListBox1.List(ListBox1.ListIndex, 4)
    SetCheckBoxes ListBox1.List(ListBox1.ListIndex, 5)        '<<<< added
    officenumber.Value = ListBox1.List(ListBox1.ListIndex, 6)
    cellnumber.Value = ListBox1.List(ListBox1.ListIndex, 7)     

End Sub

我想从ListBox1_click()找出如何确定列表框中所选项目的行#。一旦我解决了这个问题,我将对update sub进行编码,在其中找到所选项目的行#,然后我会重新输入文本框中的信息并更新信息排。

当我执行find时,我考虑在隐藏的工作表中存储行#但我不知道如何将found的行#与什么&#39;已在listbox

中选择

希望......这是有道理的,如果不是,请告诉我!

2 个答案:

答案 0 :(得分:2)

我找到了解决此问题的方法 - 我已经搜索了一个额外的列表列来存储row#的{​​{1}}。然后我在userform中创建了另一个输入行#:

的文本框

因此,在found sub中,我添加了以下行findnext(),并为listbox添加了另一行。 `listbox1.list(listbox1.listcount-1,8)= storerownumber

并在storerownumber = findnext.row子内添加了以下行:listbox1_click()

并制作了一个新的rownumber.value = listbox1.list(listbox1.listindex,8)并添加了以下几行:

sub update_click()

它工作正常!

答案 1 :(得分:1)

据我所知,您必须遍历 ListBox 中的所有行,因为您可以进行多选。

For r = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(r) Then
        Debug.Print "You selected row #" & r + 1
    End If
Next
相关问题