Hot to pass SQL query from Access form to external database ? - sql

I have database created in postgreSql and working on front-end application using microsoft access forms. I want to send a query on a press of a button:
Private Sub Command5_Click()
Dim strSQL As String
strSQL = "INSERT INTO public_failedestimate (est_num,issue_date) SELECT est_num,issue_date FROM public_estimate WHERE est_num=1 ;"
DoCmd.RunSQL strSQL
End Sub
It works when debugging, but does not when i click the button. By the way, it located in button's on click event. thx

What you have should work. If there is any possibility that the current record in the form's bound record set is dirty, then you want to ensure that the record is written to the table BEFORE you run this code.
You can add these 3 lines of code right before your RunSQL command
If me.dirty = true then
Me.dirty = false
End if

Related

Execute MySQL Select passthrough from a subform and send output recordset to a parent form

I manage a Microsoft Access 2019 Database (owned by a customer) with a form (named Mainform) whose recordset source is a MySQL passthrough query (SELECT * FROM table_on_mysql_db); each recordset (shown directly on opening Mainform) is only readable and it has three fields: one of them, description, contains text.
On double clicking on description field, a small sized subform (name Subform, containing one textvalue field named keywordDescr, plus an OK button and a Cancel button) pops up.
If I enter some words in keywordDescr (i.e. anyword) and press OK, the following passthrough query
SELECT * FROM table_on_mysql_db WHERE description LIKE '%anyword%'
is being called and the resultset ouput must be displayed in Mainform (Subform still remains opened); unfortunately, the Mainform content is not updated accordingly to the above MySQL filtered query.
The following is the VBA code called on clicking the OK button in Subform (OK is the label and the button name is button_search_description):
Private sub button_search_description_Click()
on Error goto ErrDescr
Dim qdfc as DAO.QueryDef
Dim qryPT as String
Dim ODBC_STRING as String
Dim kwd as String
kwd = Me.keywordDescr
kwd = Replace(kwd, "*", "%") '(the customer is still used to entering Access wildcard rather than MySQL wildcard!)
kwd = Replace(kwd, "'", "\'")
ODBC_STRING = "ODBC;DSN=MY_DSN_NAME" ' it works!
qryPT = "SELECT * FROM table_on_mysql_db WHERE description LIKE '" & kwd & "'"
DoCmd.setWarnings = false
Set qdfc = DBEngine(0)(0).CreateQueryDef("")
With qdfc
.Connect = ODBC_STRING
.SQL = qryPT
.ReturnsRecords = True
Me.Parent.RecordSource = qryPT
End With
Set qdfc = nothing
DoCmd.setWarnings = true
ErrDescr:
Resume Next
End Sub
Really doesn't make sense to modify query object and then set form RecordSource to that same SQL statement.
In design view, set form RecordSource to pass-through query object name or an SQL statement that uses pass-through query as source: SELECT * FROM PTQname;. Use code to modify pass-through query object to change parameters but don't change form RecordSource.
Finally, I solved the problem; #deluxeinformation gave me the right track, but I also wish to thank tho other users who gave me useful hints.
I defined a view on MySQL database named View_list, then set View_list as Mainform record source and, on Mainform load, the filtered PT query SELECT * FROM View_list WHERE F1 is executed, where F1 is the default filter where Mainform is loaded.
Similar PT query but with a different filter is being called clicking on the OK button in the Subform; the VBA code bound to this event is the following (kwd is the value entered in the input text keywordDescr of the subform Subform):
qryPT = "SELECT * FROM View_list WHERE description LIKE '" & kwd & "'"
With qdfc
.Connect = ODBC_STRING
.SQL = qryPT
.ReturnsRecords = True
Forms!Mainform.RecordSource = qryPT
End With
It's a little confusing to me what you're trying to do here but as I understand it you have a pure MySQL query (PTQName) that is the recordsource of a form (MainForm) when it is first opened. Right now this is a passthrough query defined in Access but not in MySQL. Then you want to be able to open a pop up form to filter the results you get from PTQName in MainForm. What I would do first is take the code for PTQName and create an actual view in MySQL Workbench from this (for example, call it "MyView"). Then link that view into your Access database. Access will treat this MySQL view as just another linked table. Set the recordsource of your MainForm to the name of this view so when it opens it displays records from your view. When you want to filter the records shown in your MainForm using your popup form, either use MainForm's Filter and FilterOn properties, or set MainForm's recordsource = "select * from MyView where ...". I am not seeing a need to even use a pass-through query here, let alone modify its SQL at runtime. But if I am misunderstanding please let me know!

MS Access VBA Update Query to Clear All Check Boxes On a Form Not Working

I have a button on my MS Access form that uses VBA to update the modified date/time stamp on all records on a datasheet style form that have a checkbox checked in a field called "Confirm Existing Update". After it makes these updates, it is supposed to clear all of the check boxes. This is currently accomplished via a simple SQL update query that executes via VBA once the date/timestamps have been updated:
"Update [CMO Deviations Tracker] SET [CMO Deviations Tracker].[Confirm Existing Update] = FALSE WHERE [CMO Deviations Tracker].[Confirm Existing Update] = TRUE"
The problem is that the query doesn't seem to want to clear the last checkbox checked (in the last row that was interacted with). I've tested the query by copy/pasting it into a blank query design window and it works perfectly there (clears all check boxes, including the final one clicked). So far, I've attempted to add the following to my form button's VBA code:
Shifting the record to the next line before running the Update query via "Me.Recordset.MoveNext"
Saving the last record interacted with via "If Me.Dirty Then Me.Dirty = False"
I added "Forms![CMO Deviations Tracker].Requery" to the end of the code to ensure that I was seeing the latest info
None of these seem to result in the clearing of the last checkbox checked. What could be causing this?
EDIT: I just tried running my separate Update query while the form was open immediately after trying and failing with the button. It failed to remove the last checkbox due to a "lock violation". Interesting...
EDIT2: So the only thing that I've found to work (as a manual workaround) is to check the boxes for all of the rows that I want to update the timestamp for, and then check and uncheck the box for one additional row before clicking the button. Access will then clear all of the desired check boxes like it's supposed to.
EDIT3: Just a point of clarity. The updating of the timestamp on the last record checked appears to work perfectly. It seems like, for whatever reason, it's only the "Confirm Existing Update" checkbox field that is getting locked. Thinking that it could be the method being used, I attempted to clear these checkboxes by editing the Recordset and using a loop to make the "Confirm Existing Update" field for each of the rows in the Recordset equal to "False". It still seems to clear all check boxes except the last one, only this time, the vba code will error out on the final line by saying "Could not update | currently locked". Same error, completely different implementation.
EDIT4: Updating the "Record Locking" property of the form to either "Edited Record" or "No Locks" seems to fix the issue, but only if done as part of the button click code. If I put VBA to update this property in the "On Open" event trigger of the form, or simply update the property in the GUI, it doesn't seem to fix the issue - even with "No Locks" set as the default property. What the heck?
EDIT5: Per request, the following is the VBA from my button. Please note that I've updated the methodology to update the check boxes using a DAO.Recordset, rather than the original SQL Update query.
Private Sub Command187_Click()
Dim Temp_ID As String
Dim DBS_Temp1 As DAO.Database
Dim DevTracker As DAO.Recordset
Dim DevUpdates As DAO.Recordset
If MsgBox("This will confirm that the latest update provided is still current for all items with the 'Confirm Existing Update' box checked above. Are you sure that you want to do this?", vbYesNo) = vbYes Then
Set DBS_Temp1 = CurrentDb
Set DevTracker = DBS_Temp1.OpenRecordset("CMO Deviations Tracker")
Set DevUpdates = DBS_Temp1.OpenRecordset("Deviation Updates")
DevTracker.MoveFirst
DevUpdates.MoveFirst
Do Until DevTracker.EOF = True
If DevTracker![Confirm Existing Update] = True Then
DevUpdates.MoveFirst
Temp_ID = "[Deviation ID] = '" & DevTracker![Deviation ID] & "'"
DevUpdates.FindLast (Temp_ID)
DevUpdates.Edit
DevUpdates![Status Update] = DevUpdates![Status Update] & " "
DevUpdates![Status Update] = Left(DevUpdates![Status Update], Len(DevUpdates![Status Update]) - 1)
DevUpdates.Update
DevTracker.Edit
DevTracker![Confirm Existing Update] = False
DevTracker.Update
End If
DevTracker.MoveNext
Loop
DevUpdates.Close
DevTracker.Close
Set DevUpdates = Nothing
Set DevTracker = Nothing
Set DBS_Temp1 = Nothing
MsgBox "Existing updates for the selected deviations have been confirmed."
Else
DevTracker.MoveFirst
Do Until DevTracker.EOF = True
DevTracker.Edit
DevTracker![Confirm Existing Update] = False
DevTracker.Update
DevTracker.MoveNext
Loop
MsgBox "Update Confirmation Cancelled."
Forms![CMO Deviations Tracker].Requery
Exit Sub
End If
Forms![CMO Deviations Tracker].Requery
End Sub

How to run two different DB's click event using third DB

I have two databases in MS Access having different codes, but both have unique form i.e form2. Now i have form in third database and i want run database 1 and database 2 form2 click event using this form.
I have code for this purpose on third form and code is running both db's form correctly but click event not running at that time.
My code is given below
Private Sub Command0_Click()
OpenRemoteForm "C:\Data\Offer\Chrome\Main_Ch.accdb", "Form2", "Command17_Click()"
End Sub
Function OpenRemoteForm(strDbFile As String, strFormName As String, strclick As String)
Dim objAcc As Object
Dim accFrm As Object
Dim rst As DAO.Recordset
DoCmd.RunCommand acCmdAppMinimize
Dim strBookmark As String
Set objAcc = CreateObject("Access.Application")
objAcc.OpenCurrentDatabase (strDbFile)
' objAcc.DoCmd.OpenForm strFormName
' With objAcc.Forms(strFormName)
' Set rst = .RecordsetClone
' rst.FindFirst strKeyFieldName & "=" & lngIDToFind
' If rst.NoMatch Then
' MsgBox "No Match"
' Else
' .Bookmark = rst.Bookmark
' End If
' End With
objAcc.UserControl = True
End Function
When i press button on third db form then click event should be run of DB 1 form2 and DB2 form2 simultanously.
There is no code in that procedure to call procedure in other db. If you want to call form procedure from 3rd db, procedure cannot be Private. Remove private qualifier from button Click event declaration in the two dbs.
Form name can definitely be passed in a variable and referenced that way. Must open form before calling procedure.
objAcc.DoCmd.OpenForm strFormName
Referencing form procedures is trickier. One approach is to give both buttons same name and explicitly reference that name.
objAcc.Forms(strFormName).Command17_Click
Another approach uses CallByName intrinsic function which does allow passing procedure reference in a variable.
CallByName objAcc.Forms(strFormName), strClick, vbMethod
Have to remove parentheses from the strClick parameter.
OpenRemoteForm "C:\Data\Offer\Chrome\Main_Ch.accdb", "Form2", "Command17_Click"
If you want to open db and then just hand control over to user, really don't even need all this code declaring and setting application objects. Have code behind those forms to run their own button Click event using Open or Load events. If form is set to open by default when db opens, then code in those events should execute when db opens. Methods for simply opening a file use FollowHyperlink or Shell commands.
Recommend assigning more meaningful names than defaults assigned by Access.

append data from form to column

I am working on a "issue tracker" access data base where the user enters there data through forms, create new form and edit form.
I have a comment section on my edit form which I have been requested to remained lock, for viewing purposes. So the user can only view the comments.
I have another box below that must "append" or add data to the comment section with a time and user stamp.
My approach is to create a vba code that will allow the user to enter data, and once entered will show in the locked comment section. As the user is working through a "editing" form.
I am fairly new to access and vba and unfortunately I cant find anything that I understand online.
Below is some code use and found searching online. I have but can figure out how to append ( or add ) it to the existing column. It is running fine but the data value I wish to add don't go anywhere?
Private Sub Add_Click()
Dim StrSQL As String
Dim addComments As String
' where addcomment.value is the value desire to append
addCommentStr = Me!addComment.Value
'where IssueTrack is Table, AdditionalComments is column
StrSQL = "INSERT INTO IssueTracker(AdditionalComments) VALUES ('" &
addCommentStr & "' );"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
MsgBox ("Comment Added")
End Sub
You wouldn't just keep on appending text to the same record. Where would you end?
So, skip all the code and create a form bound to the table.
Have one field for the date. Set its DefaultValue to: Now()
Set the form's property AllowEdits to: False

MS Access - SetFocus on multiple text boxes to check if data exists via SQL

The problem I'm facing:
I try to check if inserted text from multiple text boxes is already existing in a table before saving the records to avoid duplicates.
I created a form to enter new members and save them into a table. The key to avoid duplicates is to check the combination of given name, last name and birth date with existing records. (It's most likely that there won't be two person with all three criteria matching)
I have no problem to check the existence for only one text box by setting the focus on the desired box and use the SQL query IF EXISTS...
But since I would need to set focus on several text boxes(IMO) the problem occurs.
Is there a way to set focus on multiple text boxes?
The idea would be to use an IF EXISTS...AND EXISTS statement and I would need to implement the .SetFocus statement for each text box before checking its existence.
I hope you get my point and I would be glad if someone could share some knowledge. :)
Thanks in advance
There seems to be some missing information in order to find the best solution to your problem. so the below response will be based on assumptions as to how your form is working.
I'm assuming you are using an unbound form with unbound text boxes? if this is the case, then you must have a button that is the trigger for checking/adding this information to your table. lets say your command button is called "Save". You can use the following code without the need to .setfocus to any textbox.
Private Sub Save_Click()
Dim db as DAO.Database
Dim rst as DAO.Recordset
Dim strSQL as string
set db = currentdb 'This is the connection to the current database
'This is the SQL string to query the data on your table
strsql = "SELECT * " & _
"FROM [Yourtablename] " & _
"WHERE ((([YourTableName].[FirstName]) ='" & me.FormFirstNameField & "' AND ([YourTableName].[LastName]) ='" & me.FormLastNameField & "' AND ([YourTableName].[DOB]) =#" & me.FormDOBField & "#));"
set rst = db.openrecordset(strsql) 'This opens the recordset
if rst.recordcount <> 0 then
'Enter code to inform user information already exists
else
'Enter code if information does not exits
end if
rst.close 'Closes the recordset
set rst = nothing 'Frees memory
set db = nothing 'Frees Memory
End Sub
Let me know if this code works or if I need to make changes based on your scenario.