【问题标题】:VBA MS-Access For Loop Not IncrementingVBA MS-Access For 循环不递增
【发布时间】:2013-12-27 00:36:51
【问题描述】:

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

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

我添加了所有这些消息框以进行调试。我只需要那个计数器上升。不知道为什么不是。为什么这个东西不会增加?!

【问题讨论】:

  • 不,不是,它陷入了无限循环。此外,如果数据集为空,它甚至不会进入 for 循环。
  • 首次构建 RS 时,RecordCount 属性不准确,因此您的循环计数器永远不会正确。最好使用Do Until Rs.EOF 方法。计数不准确,因为将它们拖到客户端进行计数需要开销 - Access 在本地 RS 上执行相同的操作,直到滚动到视图/查询/视图的末尾才显示准确的 RecordCount。

标签: ms-access vb6 vba


【解决方案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

【讨论】:

  • 您的回答比我的要清楚得多,先生。我学到了一些东西。 :)
【解决方案2】:

使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-14
    • 2016-02-28
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多