代码循环访问MS Access中的所有记录

时间:2011-05-03 01:27:07

标签: ms-access vba

我需要一个代码来循环遍历表中的所有记录,以便我可以提取一些数据。除此之外,还可以循环过滤记录,并再次提取数据吗?谢谢!

3 个答案:

答案 0 :(得分:89)

您应该可以使用非常标准的DAO记录集循环来完成此操作。您可以在以下链接中看到一些示例:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm

我自己的标准循环看起来像这样:

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")

'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst 'Unnecessary in this case, but still a good habit
    Do Until rs.EOF = True
        'Perform an edit
        rs.Edit
        rs!VendorYN = True
        rs("VendorYN") = True 'The other way to refer to a field
        rs.Update

        'Save contact name into a variable
        sContactName = rs!FirstName & " " & rs!LastName

        'Move to the next record. Don't ever forget to do this.
        rs.MoveNext
    Loop
Else
    MsgBox "There are no records in the recordset."
End If

MsgBox "Finished looping through records."

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

答案 1 :(得分:10)

在“引用”中,导入DAO 3.6对象引用。

private sub showTableData

dim db as dao.database
dim rs as dao.recordset

set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously

'populate the table
rs.movelast
rs.movefirst

do while not rs.EOF
   debug.print(rs!myField) 'myField is a field name in table myTable
   rs.movenext             'press Ctrl+G to see debuG window beneath
loop

msgbox("End of Table")

end sub

您可以通过不同方式交换查询和过滤表等数据对象:

Trhough query:

private sub showQueryData

dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string

sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"

set db = currentDb
set rs = db.openRecordset(sqlStr)

rs.movefirst

do while not rs.EOF
  debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
  rs.movenext
loop

msgbox("End of customers from Brazil")

end sub

您还应该查找记录集对象的“Filter”属性,以仅过滤所需的记录,然后以相同的方式与它们进行交互(请参阅MS-Access代码窗口中的VB6帮助),或创建“QueryDef”对象运行查询并将其用作记录集(有点棘手)。告诉我你是否想要另一种方法。

我希望我能帮到你。

答案 2 :(得分:5)

找到一个好的代码,其中包含解释每个语句的注释。 代码见于 - accessallinone

{{1}}

在循环数据,EOF(文件结束)和BOF(文件开头)时,记录集有两个重要的属性。记录集就像表格一样,当你遍历一个记录集时,你就会按顺序从一个记录移动到另一个记录。当您在记录中移动时,EOF属性设置为false,但在尝试跳过最后一条记录后,EOF属性将变为true。对于BOF属性,它的反向相同。

这些属性告诉我们何时达到记录集的限制。