| Der folgende Code ist als Beispiel gedacht. Die Datenbank "nwind.mdb" wird in dem Verzeichnis gesucht, aus dem heraus das Beispiel gestartet wurde. Option Explicit
Private Const mcstrKeyPrefix As String = "Key "
Private Const mcstrKeySuffix As String = VBA.Constants.vbNullString
Private Property Get ApplicationPath() As String
Static strPath As String
If Len(strPath) = 0 Then
strPath = App.Path
If Right$(strPath, 1) <> "\" Then
strPath = strPath & "\"
End If
End If
ApplicationPath = strPath
End Property
Private Sub Form_Load()
Dim objCN As ADODB.Connection
Dim objRS As ADODB.Recordset
With ListView1
.View = lvwReport
.LabelEdit = lvwManual
.FullRowSelect = True
.GridLines = True
End With
Set objCN = New ADODB.Connection
With objCN
.CursorLocation = adUseClient
.Mode = adModeReadWrite
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Properties("Data Source") = ApplicationPath & "nwind.mdb"
Call .Open
End With
Set objRS = New ADODB.Recordset
With objRS
Set .ActiveConnection = objCN
.CursorLocation = adUseServer
.CursorType = adOpenForwardOnly
.LockType = adLockOptimistic
.Source = "SELECT [Personal-Nr], Nachname, Vorname " & _
"FROM Personal " & _
"ORDER BY Nachname ASC, Vorname ASC;"
Call .Open(Options:=adCmdText)
End With
Call Rs2Lv(objRS, ListView1, "Personal-Nr")
Call objRS.Close
Set objRS = Nothing
Call objCN.Close
Set objCN = Nothing
End Sub
Private Sub Rs2Lv( _
ByRef myRS As ADODB.Recordset, _
ByRef oLV As ListView, _
Optional ByVal KeyColumn As String = vbNullString)
Dim i As Long
Dim Itmx As ListItem
Call oLV.ListItems.Clear
Call oLV.ColumnHeaders.Clear
For i = 0 To myRS.Fields.Count - 1
Call oLV.ColumnHeaders.Add(, , myRS.Fields(i).Name)
Next i
While Not myRS.EOF
Set Itmx = oLV.ListItems.Add()
If Not (IsNull(myRS.Fields.Item(0).Value)) Then
Itmx.Text = myRS.Fields.Item(0).Value
Else
Itmx.Text = VBA.Constants.vbNullString
End If
For i = 1 To myRS.Fields.Count - 1
If Not (IsNull(myRS.Fields.Item(i).Value)) Then
Itmx.SubItems(i) = myRS.Fields.Item(i).Value
Else
Itmx.SubItems(i) = VBA.Constants.vbNullString
End If
Next i
If (LenB(KeyColumn) <> 0) Then
Itmx.Key = mcstrKeyPrefix & _
myRS.Fields.Item(KeyColumn).Value & _
mcstrKeySuffix
End If
Set Itmx = Nothing
myRS.MoveNext
Wend
End Sub
Private Sub ListView1_DblClick()
Dim strKey As String
If Not ListView1.SelectedItem Is Nothing Then
strKey = ListView1.SelectedItem.Key
If (LenB(strKey) <> 0) Then
strKey = Mid$(strKey, Len(mcstrKeyPrefix) + 1)
strKey = Left$(strKey, Len(strKey) - Len(mcstrKeySuffix))
Call MsgBox("Sie haben den Datensatz " & _
strKey & _
" angeklickt.", vbOKOnly Or vbInformation)
End If
End If
End SubListing 1: Recordset in einem ListView anzeigen |