1

I am trying to assign the result of the query into the variable. I have one query (lets call it "Query1") that will check various criteria. I tried it as follows.

   Dim rst As DAO.Recordset
   Dim strSQL As String
   Dim Variable1 As String

   strQry = "Query1"
   Set rst = CurrentDb.OpenRecordset(strQry)

 Variable1 = ????? 
   rst.Close
   Set rst = Nothing

I need help to complete the above code so that my variable will get the value returned by the query. Please note that my Query1 will either return a Null value or a single record.

1
  • what are the column names in query1?, also you appear to have a mismatch with strSQL and strQry Commented Dec 2, 2015 at 13:48

2 Answers 2

4

I don't see why you need a recordset for this. You could use DLookup to fetch the value returned by Query1.

Dim Variable1 As Variant
Variable1 = DLookup("[column name here]", "Query1")

I used Variant for Variable1 so that it can accept Null. If you wish to keep it as String, you can use Nz() as Andre demonstrated to transform Null to a string.

Sign up to request clarification or add additional context in comments.

Comments

2

If your query returns only a single column, and only zero or one records, you can use rst(0) to get the first field (the Fields collection is zero-based).

If rst.EOF Then
    ' covers "no records returned"
    Variable1 = ""
Else
    ' Nz() covers "NULL returned"
    Variable1 = Nz(rst(0), "")
End If

But using the field name from the query is better readable.

Variable1 = Nz(rst!myField, "")

You may also want to look into the DLookup() function, which is designed to return a single value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.