这是一个完整示例,说明如何将多个列添加到列表框。
创建表的 SQL:
DROP TABLE Test;
CREATE TABLE Test (TestID AUTOINCREMENT(1, 1),
TestName TEXT,
TestDescription TEXT,
CONSTRAINT TestPKey PRIMARY KEY (TestID));
INSERT INTO Test (TestName, TestDescription)
VALUES ('Test A', 'Testing Record A')";
INSERT INTO Test (TestName, TestDescription)
VALUES ('Test B', 'Testing Record B')";
INSERT INTO Test (TestName, TestDescription)
VALUES ('Test C', 'Testing Record C')";
按钮事件代码:
Private Sub TestButton_Click()
Dim rst As DAO.Recordset
Dim fld As DAO.Field
Dim lb As ListBox
Dim rowStr As String
Set rst = CurrentDb.OpenRecordset("Test")
Set lb = Me.TestListBox
' Set the number of listbox columns to reflect recordset fields
lb.ColumnCount = rst.Fields.Count
' Set the row source type to Value List
lb.RowSourceType = "Value List"
' Erase the listbox data so we can populate it
lb.RowSource = ""
' If ColumnHeads property is enabled, then first record is field
' names. Lets populate those.
If lb.ColumnHeads Then
rowStr = ""
' Build a string for each record
For Each fld In rst.Fields
rowStr = rowStr & replace(fld.Name,",","") & ","
Next
' Strip final comma
rowStr = Left(rowStr, Len(rowStr) - 1)
' Add each record (all fields) at once.
lb.AddItem rowStr
End If
' Loop through each record
Do Until rst.EOF
' Build a record string and add it
rowStr = ""
For Each fld In rst.Fields
rowStr = rowStr & replace(fld.Value,",","") & ","
Next
rowStr = Left(rowStr, Len(rowStr) - 1)
lb.AddItem rowStr
rst.MoveNext
Loop
' Close and release objects
rst.Close
Set fld = Nothing
Set rst = Nothing
Set lb = Nothing
End Sub
如果您希望更改列表框的内容,您需要删除并重建列表框的记录源属性。以我的经验,当涉及多列时尝试修改单个行 - 永远行不通。
希望这会有所帮助。