Search code examples
ms-accessvbams-access-2007

loop through access form and print each value in msgbox


I have a form based on myquery that looks like this:

name color

tom    red
mike   blue
joe    red  

Say I want to click a button and have a msgbox appear with the text "tom", then immediately upon closing that text box another appears with "mike" and closing again will show the last msgbox "joe", is there a way to do this with a loop? I found a similar question on stackoverflow but that code only produced the first record, "tom" three times. Thanks!


Solution

  • I set up a button on the form.

    In the On Click event on the Event Tab in the Properties window of the button, I used this code:

    Private Sub Command6_Click()
    
    Dim rs As DAO.Recordset
    
    Set rs = Me.RecordsetClone
    
    Do While Not rs.EOF Or rs.BOF
        MsgBox rs!name
        rs.MoveNext
    Loop
    
    Set rs = Nothing
    
    End Sub
    

    This makes a clone of the Recordset behind the form, and iterates through each of the records, displaying what you asked for.

    To Wayne's credit, I was a little surprised we didn't have to change rs!name to rs![name] because it's a reserved word. And he's right - you should stay away from using them as field (column) names.