动态记录集填充文本框

时间:2014-10-01 19:57:16

标签: sql access-vba ms-access-2010 recordset

从日期列表中,我需要选择不同的日期,添加365天,然后在每个可能的日期填充文本框。

我认为我需要循环使用记录集,而且我已经做到了这一点,但我不确定下一步是什么。

Private Sub Form_Load()

Dim db As Database
Dim rs As Recordset
Dim i As Long

Set db = CurrentDb
Set rs = db.OpenRecordset("qryListBox")

If rs.EOF And rs.BOF Then
Else
    Do While Not rs.EOF
        For i = 0 To rs.Fields.Count - 1

            ' get list of dates
            ' if there is more than one date, populate subsequent boxes
            me.txtAnnv1.Value = DateAdd('d',365,[sdrdate])

        Next i
        rs.MoveNext
    Loop
End If

rs.Close
Set rs = Nothing
Set db = Nothing

End Sub

如果我有:

+------+-----------+
| NAME |  SDRDATE  |
+------+-----------+
| Jane |  02/02/12 |
| Jane |  03/03/12 |
| Jane |  04/04/14 |
| Jane |  04/04/14 |
+------+-----------+

我希望看到:

txtAnnv1 = 02/03/13
txtAnnv2 = 03/04/13
txtAnnv3 = 04/05/15

1 个答案:

答案 0 :(得分:0)

我相信以下内容会让你非常接近。这假设你的文本框已经存在。它将首先隐藏所有以名称" txtAnnv"开头的文本框。并明确他们的价值观。然后,它会将记录集中的值分配给每个文本框,并在其进行时取消隐藏。

Private Sub Form_Load()

Dim db As Database
Dim rs As Recordset
Dim i As Long
Dim ctrl as Control


'Assuming that text boxes are already created and are named txtAnnv1, txtAnnv2, etc.. 
'Empty and hide all of the txtAnnv* text boxes
For each ctrl in me.Controls
    if left(ctrl.name,7) = "txtAnnv" then
        ctrl.visible = false
        ctrl.value = ""
    end if
Next ctrl

Set db = CurrentDb
Set rs = db.OpenRecordset("qryListBox")

If rs.EOF And rs.BOF Then
Else
    i = 1
    Do While Not rs.EOF
        'Set the value of each textbox to 1 year from the date in the recordset        
        me.controls("txtAnnv" & i).value = DateAdd('d', 365, rs.Fields(1).value)

        'unhide textbox
        me.controls("txtAnnv" & i).visible = true

        'iterate the counter that steps up to the next textbox
        i = i + 1
        rs.MoveNext
    Loop
End If


rs.Close
Set rs = Nothing
Set db = Nothing

End Sub