更新时间:2023-12-01 18:29:58
我个人使用以下代码显示记录集.
Personally, I use the following code to display recordsets.
就像达伦的答案一样,我创建了一个名为frmDynDS的表单,默认视图设置为数据表视图,并使用以下代码向其中添加了255个控件(在表单处于设计状态时运行)视图):
Like Darren's answer, I have created a form, which I've named frmDynDS, with the default view set to datasheet view, and I've added 255 controls to it using the following code (run while the form is in design view):
Dim i As Long
Dim myCtl As Control
For i = 0 To 254
Set myCtl = Application.CreateControl("frmDynDS", acTextBox, acDetail)
myCtl.Name = "Text" & i
Next i
然后,我将以下代码添加到表单的模块中:
Then, I've added the following code to the form's module:
Public Myself As Object
Public Sub LoadRS(myRS As Object)
'Supports both ADODB and DAO recordsets
Dim i As Long
Dim myTextbox As textbox
Dim fld As Object
i = 0
With myRS
For Each fld In myRS.Fields
Set myTextbox = Me.Controls("Text" & i)
myTextbox.Properties("DatasheetCaption").Value = fld.Name
myTextbox.ControlSource = fld.Name
myTextbox.ColumnHidden = False
myTextbox.columnWidth = -2
i = i + 1
Next fld
End With
For i = i To 254
Set myTextbox = Me.Controls("Text" & i)
myTextbox.ColumnHidden = True
Next i
Set Me.Recordset = myRS
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set Myself = Nothing 'Prevent memory leak
End Sub
然后,我在公共模块中获得了以下代码:"
Then, I've got the following code in a public module:"
Public Sub DisplayRS(rs As Object)
Dim f As New Form_frmDynDS
f.LoadRS rs
f.Visible = True
Set f.Myself = f
End Sub
完成所有这些设置后,显示记录集非常简单.只需执行以下操作:
After you have all this set up, displaying recordsets is very simple. Just do the following:
DisplayRS CurrentDb.OpenRecordset("SELECT * FROM EXPORT_CERTIFICATION WHERE EXPORT_CERTIFICATION.CertificationStatus = 'Certified'")
这将打开表单,显示适当数量的控件,设置标题,调整单元格宽度以容纳标题,然后将控件绑定到记录集.该表单将一直保存到关闭,您可以使用此代码同时打开多个记录集.
This will open up the form, make the appropriate amount of controls visible, set the caption, adjust cell width to accommodate the caption, and then bind the controls to the recordset. The form will persist until closed, and you can open up multiple recordsets simultaneously with this code.
请注意,运行此代码时不能在记录集中使用参数,因为它将在过滤/排序时崩溃.
Do note that you can't use parameters in the recordset when running this code, as it will crash on filtering/sorting.