I have searched and have found a lot of information on using requery on a subform, but I can't seem to find anything that indicates attempting to requery the active form with a new recordset.
I have a form based on a query. I am using an unbound text box to capture the address which needs to be searched then changing the sql statement in the query to locate the records then attempting to use me.requery to load the new results.
The code is updating the sql statement, but the form is not requerying with the new record results. My code is below.
I am fairly new to access and VBA, and appreciate any wisdom you may have. Also, is there ANYTHING that I could be doing in other code which would cause this to fail?
Private Sub Command51_Click()
Dim d As DAO.Database
Dim q As DAO.QueryDef
Dim Addy As String
Dim Search As String
Set d = CurrentDb()
Set q = d.QueryDefs("SQL_Search")
If IsNull(Me!Addy) Then
MsgBox ("Please select a valid address from the list and try again.")
GoTo CleanUp
Else: End If
Addy = Me!Addy
Search = "select * from dbo_ECNumberVerify Where (((dbo_ECNumberVerify.invalidrecord)=False) AND ((dbo_ECNumberVerify.updated)=False) AND ((dbo_ECNumberVerify.Locations) Like '*" & Addy & "*'));"
'Send SQL SP execute command.
q.SQL = Search
Me.Requery
CleanUp:
Set q = Nothing
Set db = Nothing
End Sub
In your example you have a query, but the query is never set or attached to the forms record source in "any way". So the “query” acts independent from the form data source.
You can simply stuff the sql directly into the forms reocrdsouce like this:
Me.RecordSource = Search
(so you don’t need all of your existing code, nor do you need the queryDef.
And when you set the forms SQL directly as per above, then a requery is done automatic for you. So the code required will look like this:
Dim strSearch As String
If IsNull(Me.Addy) Then
MsgBox ("Please select a valid address fromthe list and try again.")
Exit Sub
End If
strSearch = "select * from dbo_ECNumberVerify WHERE " & _
"(invalidrecord = False) AND (updated = False) AND " _
"(Locations Like '*" & Addy & "*')"
Me.RecordSource = strSearch
So you don't need much code, and you really don't need to use + declare the querydef at all.
Related
So, being newish to access and only using VBA in excel up until a few months ago there are quite a few commands I have absolutely 0 idea on how to use/correctly write syntax.
Problem: I have a saved query (qry_ExcelExport) which at the moment is just:
SELECT '*' FROM tbl_Contacts
What I want to do is use VBA to add/change the WHERE clause based on a user form control.
Something like:
If me.txt_Flag = "DP Delegate" then 'WHERE [DP-DEL] = True' (or = -1)
Elseif me.txt_Flag = "DP Sponsor" then 'WHERE [DP-SPON] = True' (or = -1)
And so on. (I understand that the syntax above is 100% incorrect, that's just what I'm hoping to achieve)
Using the power of the internet I managed to come across this code:
‘To change the Where clause in a saved query
Dim qdf as QueryDef
Dim db as Database
Set db = CurrentDB
Set qdf = db.QueryDefs("YourQueryName")
qdf.SQL = ReplaceWhereClause(qdf.SQL, strYourNewWhereClause)
set qdf = Nothing
set db = Nothing
Public Function ReplaceWhereClause(strSQL As Variant, strNewWHERE As Variant)
On Error GoTo Error_Handler
‘This subroutine accepts a valid SQL string and Where clause, and
‘returns the same SQL statement with the original Where clause (if any)
‘replaced by the passed in Where clause.
‘
‘INPUT:
‘ strSQL valid SQL string to change
‘OUTPUT:
‘ strNewWHERE New WHERE clause to insert into SQL statement
‘
Dim strSELECT As String, strWhere As String
Dim strOrderBy As String, strGROUPBY As String, strHAVING As String
Call ParseSQL(strSQL, strSELECT, strWhere, strOrderBy, _
strGROUPBY, strHAVING)
ReplaceWhereClause = strSELECT &""& strNewWHERE &""_
& strGROUPBY &""& strHAVING &""& strOrderBy
Exit_Procedure:
Exit Function
Error_Handler:
MsgBox (Err.Number & ": " & Err.Description)
Resume Exit_Procedure
End Function
And that first line... that very first line "To change the Where clause in a saved query" indicates that this is EXACLY what I need.
But, there is no walk-through or step-by-step beginners guide to understanding this code, the syntax or more importantly how to tie it in with a form control and it is not one I've ever used or heard of before.
EDIT: The saved query qry_ExcelExport is used in a funtion to export data
Call exportTable("qry_ExportExcel")
Where I'm calling
Public Sub exportTable(tName As String)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, tName, saveFileAs, True
End Sub
I need the ability to modify the where so that when I export it includes that clause as at the moment there is no WHERE clause so exports just take all the data.
It is normally neither needed nor practical to modify saved queries for filtering.
What you do instead is apply the filter to the form:
If me.txt_Flag = "DP Delegate" then
strFilter = "[DP-DEL] = True"
Elseif me.txt_Flag = "DP Sponsor" then
strFilter = "[DP-SPON] = True"
Else
strFilter = ""
End If
Me.Filter = strFilter
Me.FilterOn = (strFilter <> "")
Or if you need the query for something else, you can apply the filter to the query.
Set rs = DB.OpenRecordset("Select * From MySavedQuery Where " & strFilter)
Edit
If the query is used for export, it is actually one of few situations, where modifying the query is useful.
If the query is as simple as in your question, you can simply set the full SQL:
strSql = "SELECT * FROM tbl_Contacts WHERE " & strFilter
db.QueryDefs("qry_ExportExcel").SQL = strSql
Call exportTable("qry_ExportExcel")
or if the base query is more complex, use two queries: a constant one (qry_ExportExcel_Base) and a dynamic one (qry_ExportExcel)
strSql = "SELECT * FROM qry_ExportExcel_Base WHERE " & strFilter
etc. as above
I am trying to get a record based on the value contain within the textbox on a form. i.e i type in the information into the textbox and other values associated with that value are returned to other textbox on the form.
I thought this would be easy but can't seem to get it to work.
Currently I was trying
Dim rst As DAO.Recordset
Dim SQL As String
Dim SQL2 As String
SQL = "SELECT tblmytbl.[IDCODE]"
"FROM tblmytbl " & _
"WHERE (((tblmytbl.[IDCODE]) = forms!myform!mybox.value "
Set db = CurrentDb
Set rst = db.OpenRecordset(SQL)
If Not ((rst.BOF = True) And (rst.EOF = True)) Then
Forms!myform!Text102 = rst.Fields("[Name]")
Forms!myform!Text103 = rst.Fields("[Surname]")enter code here
Note: The search information is alphanumeric and i have tried without the .value
Any help would be appreciated.
Thanks
The SQL you send to the server can't access the form. However, you can concatenate the value into the string that you send like:
" WHERE (((mytable.myfield) = '" & FixQuotes(Forms!myform!mybox.value) & "') " & _
Note, you may need to defend yourself against SQL injection, a simple (but not complete) defense would be something like:
Public Function FixQuotes(input as string) As String
FixQuotes = Replace(input,"'","''")
End Function
EDIT:
Based on your updated code, there's quite a number of changes you need to make. Beyond my statement above, the .OpenRecordset only applies to full tables, you can't use it with a SELECT statement. Instead, you have to instantiate a QueryDef. On top of that, you try to reference fields you didn't include in the query. Also, you can simplify the expression Forms!myform! to Me (which could help if you want to reuse the code somewhere else) So your code should look something like this:
Dim db as Database 'always dim everything, you should use Option Explicit'
Dim rst as Recordset 'DAO is the default anyway'
Dim qdf as QueryDef 'this object is required for queries'
Set db = CurrentDb
'prepare single-use query, to return the values you're going to use
'as mentioned before, the query doesn't have access to the form
'we can use Me since it references the form'
' use TOP 1 since you only expect 1 record'
Set qdf = db.CreateQueryDef("","SELECT TOP 1 Name,Surname FROM tblmytbl " & _
"WHERE IDCODE = '" & FixQuotes(Me.mybox.value) & "';")
Set rst = qdf.OpenRecordset(DbOpenForwardOnly)
'forwardonly since you only care about the first record'
If Not rst.EOF Then 'ForwardOnly has to start at the first record'
Me.Text102.Value = rst!Name
Me.Text103.Value = rst!Surname
'I highly suggest giving these boxes better names'
Else
'no record found'
End if
rst.Close
qdf.Close
db.Close 'close these objects, it can sometimes cause memory leaks otherwise'
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
I have this form in access, the purpose of it is to work as a front end of a table which can be edited through this form. Initially when it loads I display in the form data from a recordset with the following query:
SELECT * FROM DATA
I want to be able to filter the data on the recordset once the form is open. I tried the following VBA code to accomplish this:
Private Sub Filter_Click()
If (IsNull(Me.Find_Field) Or Me.Find_Field = "") Then
rs.Close
Set rs = db.OpenRecordset("Select * from DATA ORDER BY ID)
rs.MoveFirst
LoadData (True)
Exit Sub
End If
Set rs = db.OpenRecordset("Select * from DATA WHERE ID = " & Me.Find_Field)
rs.MoveFirst
LoadData (True) ' Function that loads the data into the form
Exit Sub
As you all can see, I reload the recordset with a new filtered query. Up to this point it works, the problems begin when I try to modify a record.
Originally, when the form loads the recordset data, I am able to edit the data and the edited data would show in the table (which is what I want). But after I apply my filter, my code gives me the Run-Time error '3027': Cannot Update. Databse or object is read-only.
I am pretty much using the same code over and over to reload data from the table and it never gave me a problem until I 'overwrote' the source of the recordset. Any idea how can I resolve this issue? Thanks
I would prefer to use a standard Access bound form because it's simpler than what you appear to be doing.
I can change the form's RecordSource from the click event of my cmdApplyFilter button.
Private Sub cmdApplyFilter_Click()
Dim strSql As String
If Len(Me.txtFind_Field & vbNullString) > 0 Then
strSql = "SELECT * FROM tblFoo WHERE id = " & _
Me.txtFind_Field & " ORDER BY id;"
Me.RecordSource = strSql
End If
End Sub
If you're concerned someone might save the form with the filtered RecordSource, you can make the form always open with the unfiltered version.
Private Sub Form_Open(Cancel As Integer)
Dim strSql As String
strSql = "SELECT * FROM tblFoo ORDER BY id;"
Me.RecordSource = strSql
End Sub
I have this code that I am trying to copy a record with in VBA. Unfortunately I cannot get it to work. I do not knw why it won't do anything.
Dim OldRecord As DAO.Recordsets, NewRecord As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT [Tote Log].* FROM [Tote Log] WHERE Number = " & _
Me.tbScannerRead.Value
Set OldRecord = CurrentDb.OpenRecordset(strSQL)
If OldRecord.Count = 1 Then
Set NewRecord = _
CurrentDb.OpenRecordset("SELECT [Tote Log].* FROM [Tote Log]")
With NewRecord
.AddNew
For i = 0 To .Fields.Count - 1
.Fields(i).Value = OldRecord.Fields(i).Value
Next i
.Fields("Number").Value = Me.tbScannerRead & "B2"
.Update
varBookMark = .Bookmark
End With
NewRecord = varBookMark
DoCmd.RunCommand acCmdSelectRecord
Me.tbMessageBox = "Added new record"
Me.tbMessageBox.Visible = True
GoodToteRead = False
Me.tbScannerRead.SetFocus
End If
I get nothing, I am trying to copying a record from the tote log and change the number from, lets say, L20444 to L20444B2 and have the same field information as the original. This is where I am so far but I get nothing. Ahy Help would be greatly, and I mean greatly, appreciated. Thanks
There are a few things that could be causing it. Here is one. Does your table have a primary key? It looks like you are trying to update the primary key to a value that already exists in the table before changing it. Is this happening on a form? If so Access can get upset at you for changing a recordset behind it's back. a me.undo() before making changes can help. Also if you are on a form you can acomplish the same thing this way. It's a bit hacky, but it is the easy way.
DoCmd.RunCommand acCmdSelectRecord
DoCmd.RunCommand acCmdCopy
DoCmd.GoToRecord , , acNewRec
DoCmd.RunCommand acCmdPaste
As an alternative, I would recommend something along these lines.
Dim sSql As String
Dim sUpdateSuffix as string
sUpdateSuffix="B2"
Const sTableName As String = "[Tote Log] "
sSql = "INSERT INTO "[Tote Log]([number],[whateverelse]) " & _
"SELECT [number]" & sUpdateSuffix & ",[whateverelse] FROM [Tote Log] WHERE Number = " & Me.tbScannerRead.Value
CurrentProject.Connection.Execute sSql
If you want to build the sql string dynamically use the same method as you already used to loop through the fields and build the query string.
me.requery will rebuild the form recordset.
Hope that helps you
Well it might actually be saving the database record but not redisplaying it; I'm having a hard time deciphering that part of the code, and I don't know what your form is bound to.
Anyway, you should open your recordsets like this:
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset, dbSeeChanges)
especially if you are using SQL Server as the backend (which you should).
Once you have saved the record, you should probably just reload the record back into your form by doing a recordset.find(), rather than trying to bookmark it. Bookmarks only work on the same recordset they originated from. This provides round-trip verification that the data was actually saved into the database.