1

What do I need to add/modify to this code to have txtDisease1 be populated with the results of strSQL? As of now the textbox populates with the SQL query. I'm sure it is a simple fix but for the life of me I can not find the answer.

Private Sub btnDNA_Click()
Dim strSQL As String

strSQL = "SELECT LastName From Patient WHERE PatientID = 1"
Me.txtDisease1.Value = strSQL

End Sub
3
  • Your strSql is literally only the text "SELECT LastName From Patient WHERE PatientID = 1" and not the executed result of the query it describes. Using the DLOOKUP function as @Emi has suggested is the simpler approach for what you're trying to do here. Commented Nov 25, 2015 at 14:06
  • I know DLookup but I need to use SQL because the queries will get more complex. Is there a way to do this? Commented Nov 25, 2015 at 18:05
  • Oh ok, see answer below. Commented Nov 25, 2015 at 19:05

3 Answers 3

3

You can use DLookup function.

Me.txtDisease1.Value = DLookup("LastName", "Patient", "PatientID = 1")
Sign up to request clarification or add additional context in comments.

1 Comment

I know DLookup but I need to use SQL because the queries will get more complex. Is there a way to do this?
2

I've not been able to test this, but I think this should work.

Private Sub btnDNA_Click()

    Dim strSQL As String
    Dim db As DAO.Database
    Dim rs As DAO.Recordset

    strSQL = "SELECT LastName From Patient WHERE PatientID = 1"

    Set db = CurrentDb
    Set rs = db.OpenRecordset(strSQL)

    Me.txtDisease1 = rs!LastName

    rs.close
    Set rs = Nothing
    Set db = Nothing

End Sub

Comments

0

For more complex lookups or to hit other data sources, you can use ADO (requires reference to Microsoft Active X Data Objects)

Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT TOP 1 LastName From Patient WHERE PatientID=1", _
    CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
If Not rs.EOF Then Me.txtDisease1.Value = rs(0)
rs.Close
Set rs = Nothing

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.