acount = Sheets("Sheet3").Cells(65536, 1).End(xlUp).Row + 1 For i = 1 To acount ListView1.ListItems.Add , , Sheets("Sheet3").Cells(i + 1, 1).Value For x = 1 To 3 ListView1.ListItems(i).SubItems(x) = Sheets("Sheet3").Cells(i + 1, x + 1).Value Next x Next i
注意 除非添加到 Microsoft DAO 3.5 对象库的“引用”,否则示例无法运行。为此,在
Project 菜单上单击 References。搜索 Microsoft DAO 3.5 对象库并单击复选框来选择。
Private Sub Form_Load()
'添加 ColumnHeaders。列宽度等于控件宽度
'除以 ColumnHeader 对象的数目。
ListView1.ColumnHeaders. _Add , , "Author", ListView1.Width / 3) ListView1.ColumnHeaders. _Add , , "Author ID", ListView1.Width / 3, _ lvwColumnCenter ListView1.ColumnHeaders. _Add , , "Birthdate", ListView1.Width / 3) ' Set View property to Report. ListView1.View = lvwReport '为数据访问对象声明对象变量。
Dim myDb As Database, myRs As Recordset '设置 Database 为 BIBLIO.MDB 数据库。
' IMPORTANT: the Biblio.mdb must be on your ' machine, and you must set the correct path to ' the file in the OpenDatabase function below. Set myDb = DBEngine.Workspaces(0) _ .OpenDatabase("c:\Program Files\VB\BIBLIO.MDB") '设置 recordset 为 "Authors" 表。
Set myRs = _ myDb.OpenRecordset("Authors", dbOpenDynaset) '声明变量以添加 ListItem 对象。
Dim itmX As ListItem '若当前记录不是最后一条记录,则添加一个 ListItem 对象。
'ListItem 对象的文本使用 author 字段。
'ListItem 对象的 SubItem(1) 使用 AuthorID 字段。
'ListItem 对象的 SubItem(2) 使用 "Year of Birth" 字段。
While Not myRs.EOF Set itmX = ListView1.ListItems. _Add(, , CStr(myRs!Author),1) 'Author 字段。
'若 AuthorID 字段不为空,则将 SubItem 1 设置为此字段。
If Not IsNull(myRs!Au_id) Then itmX.SubItems(1) = CStr(myRs!Au_id) ' Author ID。
End If '若 birth 字段不为空,则将 SubItem 2 设置为此字段。
If Not IsNull(myRs![Year Born]) Then itmX.SubItems(2) = myRs![Year Born] End If myRs.MoveNext '移动到下一条记录。
WendEnd Sub