Access 2010 VBA query a table and iterate through results

后端 未结 3 636
独厮守ぢ
独厮守ぢ 2020-12-14 09:45

I have a query that I want to execute against a table. With the results I want to do something. In my head the pseudo code is:

var q = \"select * from table          


        
3条回答
  •  太阳男子
    2020-12-14 10:27

    I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:

    Dim cn As ADODB.Connection
    Dim cmd As ADODB.Command
    Dim prm As ADODB.Parameter
    Dim rs As ADODB.Recordset
    Dim colReturn As New Collection
    
    Dim SQL As String
    SQL = _
        "SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
        "c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
        "FROM tblClient AS c " & _
        "WHERE c.ClientID = @ClientID"
    
    Set cn = New ADODB.Connection
    Set cmd = New ADODB.Command
    
    With cn
        .Provider = DataConnection.MyADOProvider
        .ConnectionString = DataConnection.MyADOConnectionString
        .Open
    End With
    
    With cmd
        .CommandText = SQL
        .ActiveConnection = cn
        Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
        .Parameters.Append prm
    End With
    
    Set rs = cmd.Execute
    
    With rs
        If Not .EOF Then
            Do Until .EOF
                mstrLastName = Nz(!LastName, "")
                mstrFirstName = Nz(!FirstName, "")
                mstrMI = Nz(!MI, "")
                mdDOB = !DOB
                mstrSSN = Nz(!SSN, "")
                mlngRaceID = Nz(!RaceID, -1)
                mlngEthnicityID = Nz(!EthnicityID, -1)
                mlngGenderID = Nz(!GenderID, -1)
                mbooDeleted = Deleted
                mdRecordDate = Nz(!RecordDate, "")
    
                .MoveNext
            Loop
        End If
        .Close
    End With
    
    cn.Close
    
    Set rs = Nothing
    Set cn = Nothing
    

提交回复
热议问题