Код для циклического прохождения всех записей в MS Access - PullRequest
40 голосов
/ 03 мая 2011

Мне нужен код, чтобы перебрать все записи в таблице, чтобы я мог извлечь некоторые данные. В дополнение к этому, возможно ли также проходить через отфильтрованные записи и, опять же, извлекать данные? Спасибо!

Ответы [ 3 ]

89 голосов
/ 03 мая 2011

Вы должны быть в состоянии сделать это с помощью довольно стандартного цикла набора записей 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
10 голосов
/ 03 мая 2011

В разделе «Ссылки» импортируйте ссылку на объект 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

Вы можете взаимодействовать с объектами данных, такими как запросы и отфильтрованные таблицы, по-разному:

Общий запрос:

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

Вам также следует искать свойство «Фильтр» объекта набора записей, чтобы фильтровать только нужные записи и затем взаимодействовать с ними таким же образом (см. Справку VB6 в окне кода MS-Access), или создать объект «QueryDef». выполнить запрос и использовать его как набор записей (немного сложнее). Скажите мне, если вы хотите еще один подход.

Надеюсь, я помог.

5 голосов
/ 27 февраля 2016

Нашел хороший код с комментариями, объясняющими каждое утверждение. Код найден на - accessallinone

Sub DAOLooping()
On Error GoTo ErrorHandler

Dim strSQL As String
Dim rs As DAO.Recordset

strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make 
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)

Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!! 
'In English, this means that we have opened up a recordset 
'and can access its values using the rs variable.

With rs


    If Not .BOF And Not .EOF Then
    'We don’t know if the recordset has any records, 
    'so we use this line of code to check. If there are no records 
    'we won’t execute any code in the if..end if statement.    

        .MoveLast
        .MoveFirst
        'It is not necessary to move to the last record and then back 
        'to the first one but it is good practice to do so.

        While (Not .EOF)
        'With this code, we are using a while loop to loop 
        'through the records. If we reach the end of the recordset, .EOF 
        'will return true and we will exit the while loop.

            Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
            'prints info from fields to the immediate window

            .MoveNext
            'We need to ensure that we use .MoveNext, 
            'otherwise we will be stuck in a loop forever… 
            '(or at least until you press CTRL+Break)
        Wend

    End If

    .close
    'Make sure you close the recordset...
End With

ExitSub:
    Set rs = Nothing
    '..and set it to nothing
    Exit Sub
ErrorHandler:
    Resume ExitSub
End Sub

Наборы записей имеют два важных свойства при циклическом просмотре данных: EOF (конец файла) и BOF (начало файла). Наборы записей похожи на таблицы, и когда вы перебираете одну из них, вы буквально переходите от записи к записи в последовательности. При перемещении по записям для свойства EOF устанавливается значение false, но после того, как вы попытаетесь пройти последнюю запись, свойство EOF становится истинным. То же самое работает в обратном порядке для свойства BOF.

Эти свойства позволяют нам знать, когда мы достигли пределов набора записей.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...