简体   繁体   English

VBA Excel - 遍历 ListView 控件

[英]VBA Excel - looping through ListView Controls

I have 4 ListViews on the UserForm .我在UserForm上有 4 个 ListViews 。 Is it possible to check which ListView is active/selected as on the code below?是否可以按照下面的代码检查哪个ListView处于活动/选择状态?

Private Sub CommandButton8_Click()
    For i = 1 To 4
        If me."ListView" & i) is selected Then
            MsgBox me("ListView" & i ).Name
        End If
    Next i
End Sub

It is not working with ListView.SelectedItem .它不适用于ListView.SelectedItem I don't actually understand why?我其实不明白为什么? Even if ListView is not selected, MsgBox pops up first ListView item as SelectedItem .即使没有选择ListViewMsgBox也会弹出第一个ListView项作为SelectedItem

For i = 1 To 4
    If Me("ListView" & i).SelectedItem > 0 Then
        MsgBox "listview" & i & " selected item is " & Me("ListView" & i).SelectedItem
    End If
Next i

First, when the data is loaded onto a listview control, the first item is automatically selected.首先,当数据加载到列表视图控件上时,第一项被自动选中。 So, to avoid this from happening, set the Selected property for the first item to False after you've added the data.因此,为避免发生这种情况,请在添加数据后将第一项的 Selected 属性设置为 False。 For example...例如...

Me.ListView1.ListItems(1).Selected = False

or或者

Me.Controls("ListView" & i).ListItems(1).Selected = False

Then you can use the following code to loop through each listview control, and then for each one loop through each item to check which one is selected...然后你可以使用下面的代码来循环遍历每个listview控件,然后for each循环遍历每一项来检查选择了哪一个...

Private Sub CommandButton1_Click()
    
    Dim i As Long
    For i = 1 To 4
        
        Dim lv As ListView
        Set lv = Me.Controls("ListView" & i)
        
        With lv
            Dim j As Long
            For j = 1 To .ListItems.Count
                If .ListItems(j).Selected Then
                    MsgBox lv.Name & " - " & .ListItems(j).Text
                    Exit Sub 'optional
                End If
            Next j
        End With
        
    Next i
    
End Sub

If you can have more than one item selected, and you want to display the name of each one, remove Exit Sub from the code.如果您可以选择多个项目,并且希望显示每个项目的名称,请从代码中删除Exit Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM