MS Access: Subform Datasheet - Variable RecordSources - ms-access

I have a subform datasheet whose RecordSource can be variable. My database constructs an SQL query based on user selections (a different collection of columns with each query). The resulting query is intended to be the RecordSource for a datasheet on a subform. (Read-only view for user)
Problem:
The various queries produce the desired results when run on their own
Setting a resulting query as the datasheet's RecordSource does not produce any result (no columns/rows)
I suspect I need to insert the query's attributes into the subform in order to see any results (much like "Add Existing Fields" in the menu strip).
Question:
Any pointers to get me off square one?
Thank you!

Remove the datasheet form from your subform object and leave the source object property empty.
Create a new query (sql doesn't matter) and name it qryTemp (or whatever you like).
Then whenever you want to set the source for the subform, use this
CurrentDb.QueryDefs("qryTemp").SQL = "<your new sql here>"
<yoursubformobject>.SourceObject = "Query.qryTemp".

Here is an example I use to populate a sub-form:
Private Sub cmdFind_DisplayName_Click()
Dim dbs As Database, rstPatient As Recordset
Dim txtDisplayName, strQuote As String
strQuote = Chr$(34)
On Error GoTo ErrorHandler
Me.OrderBy = "DISPLAYNAME"
Me.OrderByOn = True
Set dbs = CurrentDb
Set rstPatient = Me.RecordsetClone
txtDisplayName = Trim(InputBox("Please Enter Patient Name ", "Patient Find By Name"))
txtDisplayName = UCase(txtDisplayName) & "*"
If IsNull(txtDisplayName) Then
MsgBox ("No Patient Name Entered - Please Enter a Valid Patient Name")
Else
rstPatient.FindFirst "[DISPLAYNAME] Like " & strQuote & txtDisplayName & strQuote
If Not (rstPatient.NoMatch) Then
Me.Bookmark = rstPatient.Bookmark
Me.Refresh
Else
MsgBox ("Patient Not Found - Please Enter a New Patient Name")
End If
End If
GoTo Exit_cmdFind_Click
ErrorHandler:
MsgBox LTrim(RTrim(Me.NAME)) + "." + "Patient Find By Display Name - " + "Error: " + AccessError(Err.Number)
Exit_cmdFind_Click:
rstPatient.Close
Set dbs = Nothing
Set rstPatient = Nothing
End Sub

Related

Unable to filter datasheet form after inserting value in ms access

I am using a datahseet subform in my main form for the realtime view of entries added in the table via the main form. This subform filters data on load event and checks with users windows username and compares it with data, it should only show data of respective owner. That means it willl filter the name field and shows only the entries made by the respective user(to unable users to edit each other's entries). It works well with the below code which I used in this datasheet form's vba :
Option Compare Database
Option Explicit
Dim GetUserName As String
Dim GetEmpID As String
Dim RecCount As String
Public Sub GetValues()
Dim obj1 As Object
Set obj1 = CreateObject("WScript.Network")
GetUserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
RecCount = DCount("[ID]", "Mau_con", "[AdvisorName] = '" & GetUserName & "'")
Set obj1 = Nothing
End Sub
Private Sub Form_AfterInsert()
Call Form_Load
End Sub
Private Sub Form_Load()
Call GetValues
If RecCount > 0 Then
Dim strOpen As String
strOpen = "[AdvisorName] = '" & GetUserName & "'"
Me.Filter = strOpen
Me.FilterOn = True
Me.Recordset.MoveLast
End If
End Sub
It filters the data on load but problems arises when a new user comes and login, then it will skip the if loop and will work normally, I tried to requery the form after making first entry by the new user & I also tried to call form_load in after insert event but both did not work.
But it filters the data once we close it and reopen it.
What is the best way to overcome this ?
Please ask if any other information needed.
Thanks in Advance.

Get recordset from selected records on datasheet

I have a subform with a datasheet view. On the parent form I am trying to edit records based on what is selected in the child datasheet. The forms are not linked using master/child fields.
I'm capable of getting the top row that is selected and the number of selected rows using SelTop and SelHeight like below.
Dim rs As New ADODB.Recordset
Set rs = Me.Child_Form.Form.RecordsetClone
If SelHeight > 0 Then
rs.MoveFirst
rs.Move SelectionTop - 1
For i = 1 To SelectionHeight
If Not rs.EOF Then
Debug.Print rs("ID")
rs.MoveNext
End If
Next i
End If
What I cannot do is get, say, the 10 records selected on the subform if I have filtered or sorted the form at all. The Filters and Sorts are at the form level and cannot be applied to the underlying recordset.
I've tried creating a new recordset with a query something like this
sql = "Select * from [" & Me.RecordSource & "] where " & Replace(Me.Filter, """", "'") & " order by " & Me.OrderBy
but there are multiple problems here. 1) ADO does not support the IN clause which the form filter will sometimes generate, and 2) the order order is not always the same and predictable.
How can I get a sorted, filtered recordset and find only those records which a user has selected in a datasheet view?
I am connecting to Sql Server with an ADP file.
I came up with a frustrating solution but it seems to work.
added an unbound (to my recordset) checkbox control to my subform.
named it chkSelect.
made the controlsource =IsChecked(ID)
I have this code running in the subform
Dim selectedRecords As Dictionary
Private Sub chkSelect_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If selectedRecords.Exists(Me("Analytical_ResultID").Value) Then
selectedRecords.Remove Me("Analytical_ResultID").Value
Else
selectedRecords.Add Me("Analytical_ResultID").Value, Me("Analytical_ResultID").Value
End If
chkSelect.Requery
End Sub
Private Function IsChecked(Analysis_ResultID As Long) As Boolean
IsChecked = selectedRecords.Exists(Analysis_ResultID)
End Function
Private Sub Form_Load()
If selectedRecords Is Nothing Then
Set selectedRecords = New Dictionary
End If
End Sub
This works but it's flickery and not ideal. I would much prefer another answer.

Access and Word 2010 merging one record depending on subform button clicked

I'm working on a small program in which one letter in Word needs to be create when one button in a Access subform is clicked.
The form represents one client and in the subform there are the list of commands done by this client. Next each command line (containing date and description), there is one button that trigger the maccro and create the letter. Until now, I succeed to create the word letter when one button is clicked but each command in the subform create a page in the word document.
Is it possible to keep only the command next to the button clicked and not all the command?
I was looking for that kind of command :
"SELECT * FROM [Fusion]WHERE [id_client] = " & Forms!subform!id_client
but when I do it for the subform I have one error saying that the form doesn't exist...
Thanks for your help.
--EDIT--
Here is the code, the [Fusion] is my SQL request which get all the clients and the orders related to them.
Function Publipostage()
Dim mDoc As String
Dim strSQL As String
' Path of the letter
mDoc = "C:\...\LT000006.docx"
strSQL = "SELECT * FROM [Fusion]WHERE [id_client] = " & Forms!FormPatient!id_client
Dim oApp As New Word.Application
Dim oMainDoc As Word.Document
Dim sData As String
oApp.Visible = True
sData = "C:\...\Database1.accdb"
Set oMainDoc = oApp.Documents.Open(mDoc)
With oMainDoc.MailMerge
.MainDocumentType = wdFormLetters
.OpenDataSource Name:=sData, SQLStatement:=strSQL
End With
With oMainDoc
.MailMerge.Destination = wdSendToNewDocument
.MailMerge.Execute
End With
oApp.Activate
oApp.Documents.Parent.Visible = True
oApp.Application.WindowState = 1
oApp.ActiveWindow.WindowState = 1
Set oApp = Nothing
Set oMainDoc = Nothing
Exit Function
Err_Handle:
Set oApp = Nothing
Set oMainDoc = Nothing
MsgBox "An error occurred..." & vbCrLf & vbCrLf & Err.Description
End Function
your question is a bit unclear but if the button is on the subform you can use
Me.id_client
if it is on the main form try
Forms("MAIN FORM NAME").Controls("SUB FORM NAME").Form.Controls("id_client")
Edit
Or Me.Parent.Controls("id_client")
When referencing a subform you must reference the parent form first.
If you only want to print 1 command from the list then it seems your SQL needs to change to reference that command. i.e.
"SELECT * FROM [Fusion] WHERE [id_command] = " & Me.id_command
This is just an example as I am unaware of your table structure.

Auto Populate Access Form using simple VBA code by setting a variable

I was recently given the task of creating a form that will autofill with the information from a table. The information the form autofills is selected using a primary key called ModID. I have a combo box that has a List of the ModIDs that are listed as Active.
SELECT ModID
FROM P_Review
WHERE Status = "Active"
Simple enough. I then have VBA code running on the event After Update. So after the value for the combo box is select or changed it will run this VBA code.
Option Compare Database
Option Explicit
Private Sub selectModID_AfterUpdate()
'Find the record that matches the control.
On Error GoTo ProcError
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID=" & Me.selectModID
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.RunCommand acCmdRecordsGoToNew
Me!localModID = Me.selectModID.Column(0)
End If
End With
ExitProc:
Exit Sub
ProcError:
MsgBox "Error: " & Err.Number & ". " & Err.Description
Resume ExitProc
End Sub
The code runs fine (I get no errors when I debug or run).
Now for the access text box. I would like to populate certain fields based off the variable localModID. I have a dlookup in a text box to find the information in the table P_Review.
=DLookUp("Threshold","P_Review","ModID =" & [localModID])
So the DlookUp should find the value for the column threshold, in the table P_Review, where the ModID in P_Review equals the localModID set in the VBA code. But when I go to form view and select a ModID I get the Error 3070: The Microsoft Access database engine does not recognize as a valid field name or expression. I did copy this code from another database we are already using but it fails in this new instance.
Private Sub ModID_AfterUpdate()
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID='" & Me.ModID & "'"
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.GoToRecord , , acNewRec
Me!ModID = Me.ModID
End If
End With
End Sub
This is the answer to question. I used this code to auto update.
Try
Forms!<whatever_this_form_name_is>![localModID]
in your DLOOKUP

How to Requery a subform inside a form?

I'm having a problem in which I can't requery a subform inside of a form in Access.
The form's name is frmSearch
The subform's name is SearchResults
I've tried
Private Sub Command38_Click()
Me!SearchResults.Form.Requery (or)
Me.SearchResults.Form.Requery
End Sub
My form & subform look like this:
To be clear, I'm using the "Search" button to create a string which contains the textbox and combobox values. This string creates a SQL query called qryTrialQuery. Then my subform makes a query of the qryTrialQuery and produces the results in the table bellow.
I would like to be able to press the search button and then the results appear below it immediately after. The problem is, is that the results don't appear unless I close and reopen the form.
Thanks for all your help in advance.
Update
The following is the code I used to create a query from the textbox and combobox values.
LineOne = "SELECT tblPoolPersonnel.LName, tblPoolPersonnel.FName, tblPoolPersonnel.[Tel Natel], tblPoolPersonnel.[Tel Home], tblPoolPersonnel.Email" & vbCrLf
LineTwo = "FROM (tblPoolPersonnel INNER JOIN tblDayAvailable ON tblPoolPersonnel.Code_Personal = tblDayAvailable.Code_Personal) INNER JOIN tblServiceYES ON tblPoolPersonnel.Code_Personal = tblServiceYES.Code_Personal" & vbCrLf
LineThree = "WHERE (((tblServiceYES.Service)=" & comboService & ") AND ((tblDayAvailable.Availability)=True) AND ((tblDayAvailable.Date)=" & txtDate & ") AND ((tblDayAvailable.CodeHoraire1)=" & comboCodeHoraire & "));"
Set qdf = CurrentDb.QueryDefs("myQuery")
Application.RefreshDatabaseWindow
strSQL = LineOne & LineTwo & LineThree
qdf.SQL = strSQL
qdf.Close
Set qdf = Nothing
Set dbs = Nothing
Assuming you are reconstructing the SQL of your query based on the criteria the user selected, you should just be able to do something like this:
Private Sub Command38_Click()
Dim qryTrialQuery as String
...
' code to construct the SQL SELECT statement for the query, '
' based on the criteria the user entered '
...
SubForm.Form.RecordSource = qryTrialQuery
End Sub
Setting the Subform's RecordSource will refresh the data.
You can try this:
Dim frm as Form
Set frm = frmSearch
frmSearch!SearchResults.Form.Requery