MS Access VBA - display dynamically built SQL results in datasheet subform

后端 未结 4 1575
长情又很酷
长情又很酷 2021-01-17 18:45

I have several years experience with VBA in MS Office applications (for automation and ETL processes) but have not had the need to mess with Forms in MS Access until recentl

4条回答
  •  天涯浪人
    2021-01-17 19:40

    short and sweet. Here is the code for a button that creates dynamic sql string, closes the current object (just in case its open), deletes a temporary query definition (because we need one), creates a new query definition with the new sql, changes the recordsource and Bob's your uncle.

    Private Sub btnRunSQL_Click()
      'my subform is called datasheet, i know -- dumb name.
      'a dynamic sql needs to be saved in a temporoary query. I called my qtemp
      Dim sql As String
      sql = "select * from client order by casename asc"
      'in case there is something kicking around, remove it first, otherwise we can't delete the temp query if it is still open
      Me!Datasheet.SourceObject = ""
      'delete our temporary query. Note, add some err checking in case it doesn't exist, you can do that on your own.
       DoCmd.DeleteObject acQuery, "qtemp"
      'lets create a new temporary query
      Dim qdf As QueryDef
    
      Set qdf = CurrentDb.CreateQueryDef("qtemp", sql)
      'set the subform source object
      Me!Datasheet.SourceObject = "query.qtemp"
      'and it should work.
    End Sub
    

提交回复
热议问题