VBA Listview设置和获取列名称

时间:2019-06-25 09:15:26

标签: excel vba listview

我正在尝试将记录集填充到VBA中的ListView中。 想法是将列名称添加为键,这样我以后也可以通过名称访问元素

这是我填写列表视图的方式。我只想显示一列,但其余属性的列宽为0

rs.MoveFirst
Dim fieldCounter As Integer
Dim columnWidth  As Integer
With lstProgram
    .View = lvwReport
    .Gridlines = True
    .FullRowSelect = True
    For fieldCounter = 0 To rs.Fields.count - 1
        columnWidth = 300
        If fieldCounter <> 0 Then
            columnWidth = 0
        End If
        .ColumnHeaders.Add fieldCounter + 1, rs.Fields(fieldCounter).Name, rs.Fields(fieldCounter).Name, columnWidth
    Next fieldCounter
    Do
        If Not (IsNull(rs.Fields(0).value)) Then
            Dim tmpItem As ListItem
            For fieldCounter = 1 To rs.Fields.count
                If fieldCounter = 1 Then
                    Set tmpItem = .listItems.Add(, , rs.Fields(fieldCounter - 1).value)
                Else
                    If Not IsNull(rs.Fields(fieldCounter - 1).value) Then
                        tmpItem.ListSubItems.Add text:=rs.Fields(fieldCounter - 1).value
                    Else
                        tmpItem.ListSubItems.Add text:=""
                    End If
                End If
            Next fieldCounter
        End If
        rs.MoveNext
    Loop Until rs.EOF
End With

然后我想做这样的事情...

Private Sub DisplayProgramItem(ByVal Item As MSComctlLib.ListItem)
On Error GoTo error
    '
    txtOpexID.text = Item.ListSubItems("OPEXID")
    txtName.text = Item.text
    cmbCluster.text = Item.ListSubItems("Cluster")

done:
   Exit Sub

error:
   ErrNotify Err, Me.Name, "lstProgram_ItemClick"
   Resume done
End Sub

任何想法如何实现这一目标?

我发现了一些有趣的链接,但是它们都无法解决我认为的问题,或者至少在尝试时无法解决重复键的问题

Set tmpItem = .listItems.Add(,rs.Fields(fieldCounter - 1).Name, rs.Fields(fieldCounter - 1).value)

https://social.msdn.microsoft.com/Forums/windows/en-US/b96f9fbe-e128-4b49-833d-2a5f6e678dae/access-listview-subitem-text-by-column-header?forum=winforms

https://social.msdn.microsoft.com/Forums/vstudio/en-us/6ed95bf8-6e37-4306-87a6-2267dd83c1d1/refer-to-listview-subitems-by-name?forum=vbgeneral

0 个答案:

没有答案