VBA MS-Access For Loop Not Incrementing

时间:2013-12-27 00:36:51

标签: vba vb6 access-vba

真诚地在黑暗中。我的代码:

Public Property Get rowCount() As Integer
rowCount = Counter
End Property

Public Property Let rowCount(ByRef inte As Integer)
 Counter = inte
 End Property

Private Sub Form_Timer() 'Timer
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim Caption As Field, Form As Field, Count As Integer, holder As Integer, item As String
Dim strForms() As String

Set dbs = CurrentDb
Set rs = dbs.OpenRecordset("MainMenu", dbOpenDynaset)

ReDim strForms(1 To rs.RecordCount())
If rs.RecordCount <> 0 Then
  For c = 1 To rs.RecordCount() Step 1 '!!!THIS IS THE PROBLEM!!!
   MsgBox CStr(c)
   MsgBox rs("Caption")
   strForms(c) = rs("Caption")
   rs.MoveNext
   MsgBox rs("Caption")
  Next c
End If
rowCount = 1
holder = rowCount()
If holder <= rs.RecordCount() Then
 Me.Command10.Caption = strForms(holder)
 rowCount = holder + 1
Else
 rowCount = 1
 Me.Command10.Caption = strForms(holder)
End If

End Sub

我在调试中添加了所有这些消息框。我需要的只是反击。不知道为什么不是。为什么这个东西不会增加?!

2 个答案:

答案 0 :(得分:1)

使用RecordCount属性可能是问题所在。

它实际上只计算rs.MoveNext被调用的次数。

尝试将代码切换为如下循环:

Dim L As Long
Do Until rs.EOF
    L = L + 1
    MsgBox rs.RecordCount
    MsgBox L
    rs.MoveNext
Loop

Access Recordsets并不像.NET DataTables那么容易,但它们已经存在了很长时间。

http://msdn.microsoft.com/en-us/library/office/bb208624(v=office.12).aspx

答案 1 :(得分:1)

最好的方法是使用rs.MoveFirst,rs.MoveNext和rs.EOF来检查记录的结尾。以下VBA将按您的要求执行。

'Open up a recordset on our table
Set dbs = CurrentDb
Set rs = dbs.OpenRecordset("MyTable", dbOpenDynaset)

'Did we find any records?
If rs.RecordCount > 0 Then

    'Move to first record
    rs.MoveFirst

    'Iterate through each record
    Do

        'Do stuff with the currentrecord
        MsgBox ("Next record ID is: " + CStr(rs("ID")))

        'Move to next record
        rs.MoveNext

        'Exit when we hit the end of the recordset
    Loop While rs.EOF <> True

End If

'Close the recordset
rs.Close