jueves, 14 de marzo de 2013

¿Cómo hacer consultas SQL desde VBA en Access?

Ejemplo 1: lectura secuencial

Dim db_m As Database
    Dim rs_m As DAO.Recordset
    Dim strSQL_m As String
    Dim strResult_m As String
    Set db_m = CurrentDb
    strSQL_m = "SELECT ..."
    Set rs_m = db_m.OpenRecordset(strSQL_m, dbOpenForwardOnly)
    If rs_m.RecordCount <> 0 Then
        While Not rs_m.EOF
            strResult = strResult & rs_m![Modelo]
            rs_m.MoveNext
        Wend
    End If

Ejemplo 2: lectura de un dato en particular

Dim db As Database
    Dim rs As DAO.Recordset
    Dim strSQL As String
    Dim strResult As String
    Dim VarRecords As Variant
    
    Set db = CurrentDb
    
    strSQL = "SELECT Snippet FROM dbo_Snippets WHERE ID = '" & Id_Snippet & "'"
    
    Set rs = db.OpenRecordset(strSQL)
    VarRecords = rs.GetRows(1)

Más información