Update Fields in Record Using Forms Command Button - forms

I'm new to MsAccess.
I have a table named "Tracking" which contains some fields including "OrderID", "Process1_In" and "Process1_Out".
I created a form which creates records with "OrderID" and "Process1_In".
I'm creating another form where users input an "OrderID" into a textbox named "OrderID" and click the command button where this updates the "Process1_Out" field in the Tracking table with the current date and time (using the Now() function).
I created the codes in the Form_BeforeUpdate event as follow:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Update Tracking
Set Process1_Out = Now()
Where OrderID = OrderID.Value
End Sub
However this doesn't update the record as planned. Anyone can help?

Your SQL is a string that you build, then execute. So your code would look like this:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim sql as string
sql = ""
sql = sql & "Update Tracking "
sql = sql & "Set Process1_Out = #" & Now() & "# "
sql = sql & "Where OrderID = OrderID.Value"
CurrentDB.Execute sql
End Sub

Related

How can I avoid duplicates insert of records from datagridview to SQL Server table

I have a table in SQL Server 2008 R2 where I have a table CT11. What I want is to stop inserting duplicates records in the table using cellendedit event. How can I do it because I am getting duplicates of records?
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
For Each row In DataGridView1.Rows
If cmbexam.Text = "CAT 1" Then
sqlSTR = "INSERT INTO CT11 (Admno, Name, Score) VALUES ('" & row.Cells(0).Value & "','" & row.Cells(1).Value & "','" & row.Cells(2).Value & "')"
ExecuteSQLQuery(sqlSTR)
End If
Next
End Sub
First, learn how to use SQL Command
How to use parameters "#" in an SQL command in VB
If you want the database to validate your entry then learn how to use Stored Procedure
https://mostafaelmasry.com/2015/10/03/creating-system-stored-procedure-in-sql-server-2008-r2/
In Stored Procedure add a condition that will check your entry ex;
SELECT #record = COUNT(1) FROM CT11
WHERE Admno = #Admno AND Name = #Name AND Score = #Score;
IF #record = 0
BEGIN
INSERT INTO CT11 (Admno, Name, Score) VALUES (#Admno, #Name, #Score);
END
In VB
For Each row In DataGridView1.Rows
If cmbexam.Text = "CAT 1" Then
MyCommand = New SqlCommand("StoredProcedureName", dbConn)
MyCommand.CommandType = CommandType.StoredProcedure
MyCommand.Parameters.AddWithValue("#Admno", row.Cells(0).Value)
MyCommand.Parameters.AddWithValue("#Name", row.Cells(1).Value)
MyCommand.Parameters.AddWithValue("#Score", row.Cells(2).Value)
MyCommand.ExecuteNonQuery()
End If
Next
Or follow this thread: SQL Server stored procedure and execute in VB.NET
Or you can use VB to validate the values by executing a select statement and check if there a record or not.

Populate combobox access 2007 using vba with postgresql table

I'm trying to populate a combobox with records from a table filtered by a parent combobox.
The table I want to filter is called muni and parent table is called prov. They are related by a common field (muni has a field called gid_prov that contains prov gid for each record)
First combobox stores the prov gid and shows the prov name.
Both tables are in a database from postgresql connected to access by an DSN file using ODBC.
I have tried many options, and none is correct.
First I tried a simple option. This code is useless now
Private Sub PROV_Change()
MUNI.RowSourceType = "Table/Query"
MUNI.RowSource = "select * from memoria.muni where gid_provs =" & PROV
MUNI.Requery
MUNI.SetFocus
MUNI.Text = ""
End Sub
PROV is the name of the parent combobox that stores the prov gid. And MUNI the combobox I want to populate.
Other option I tried was creating a query with an sql statement, this is the code right now, i tried with the OpenRecordsetOutput, but is not working. I can access the database and get the fields, but I can't populate the combobox MUNI
Private Sub PROV_Change()
Dim oDb As DAO.Database
Dim oRs As DAO.Recordset
dbconnect = "ODBC;DRIVER=PostgreSQL ANSI;UID=***;PWD=***;PORT=5432;SERVER=127...;DATABASE=memoria_historica;DSN=C:\Users\***"
Set oDb = OpenDatabase("", False, False, dbconnect)
Dim sql As String
sql = "select gid,nombre from memoria.municipios m where m.gid_provs =" & PROV & "order by m.nombre;"
Set oRs = oDb.OpenRecordset(sql, dbOpenSnapshot, dbSQLPassThrough)
Me.muni2.RowSource = ""
If oRs.RecordCount > 0 Then
With oRs
.MoveFirst
.MoveNext
Do While Not .EOF
muni2.AddItem .Fields("nombre").Value
.MoveNext
Loop
End With
End Sub
Worked fine tih the support of #Thaippo. Thanks
You can you DAO library.
You could you DAO. Database and DAO. Recordset like:
Dim oDb as DAO.Database
Dim oRs as DAO.Recordset
Your second block of codes could do the work.
Set oDb = OpenDatabase("", False, False, dbconnect)
Dim sql As String
sql = "select m.nombre from memoria.muni
m,memoria.prov p where st_within(m.the_geom,p.the_geom) and p.gid =" & PROV ";"
Set oRs = oDb.Openrecordset(sql)
If oRs.Recordcount > 1 Theb
With oRs
.Movelast
.Movefirst
Do while not.EOF
PROV.Additem . Fields("nameOfFieldsYouNeed"). Value
.Movenext
Loop
End With
End if
And it's would be a good idea to clear the combox box before adding new items in it.

how to use a form to navigate to specific query based on what is entered on the msgbox?

So I have a Access database with a table transaction.
On the table there is a column called profit filtered by month.
I have already made a few queries to calculate the total profit on monthly basis (eg. Jun,July,Aug)
So is it possible to create a form with a pop-up message box, and by enter a month number on the box and click, it will lead to a specific query?
I think it is a good idea but I know little about ACCESS programing so any comment are much appriciated!
You can use VBA's InputBox function to create the pop-up. If your queries already exist in the database, you could then use the results of that function to determine which query to open. For example:
Public Sub OpenExistingQuery()
Dim intMonth As Integer
intMonth = InputBox("Please enter a month number:", "Enter Month Number")
DoCmd.OpenQuery "qryMonth" & intMonth, acViewNormal
End Sub
Alternatively, you could use the results of the InputBox function to dynamically build a query, and then open it:
Public Sub OpenDynamicQuery()
Const strQueryName As String = "qryDynamicMonth"
Dim db As DAO.Database: Set db = CurrentDb
Dim qdf As DAO.QueryDef
Dim intMonth As Integer
intMonth = InputBox("Please enter a month number:", "Enter Month Number")
On Error Resume Next
DoCmd.Close acQuery, strQueryName, acSaveNo
DoCmd.DeleteObject acQuery, strQueryName
On Error GoTo 0
Set qdf = db.CreateQueryDef(strQueryName)
qdf.SQL = "SELECT * FROM your_table_name WHERE your_monthnumber_column = " & intMonth
qdf.Close
DoCmd.OpenQuery strQueryName, acViewNormal
Set qdf = Nothing
Set db = Nothing
End Sub
Please note that the above functions are of the "quick-and-dirty" variety. They really need better error handling, sanitation of user input, etc. But hopefully you get the idea, and can take care of that on your own.

Access Form / VBA: Concatenated Field Name

I created a Form in Access, and within this form there is a button which will allow the user to insert a record into a table ("Tbl")
The format of this table is:
Report1_Field1
Report1_Field2
Report2_Field1
Report2_Field2 (and so on)
The Form will ask the user to:
- Select the report name ("ReportName"); which could be "Report1" or "Report2"
- Input a value for Field1 and Field2
The VBA code behind the button is as follows:
Private Sub ButtonUpdate
Dim NameReport as String
Dim FirstField as String
Dim SecondField as String
NameReport = ReportName
FirstField = ReportName & "_Field1"
SecondField = ReportName & "_Field2"
DoCmd.RunSQL "INSERT INTO tbl (FirstField, SecondField) VALUES (Field1, Field2)"
End Sub
I am however getting the Run-Time error 3127: The INSERT INTO statement contains the following unknown field name: 'FirstField'. Make sure you have typed the name correctly, and try the operations again.
Thoughts?
The SQL string is reading "FirstField" and "SecondField" as literal text instead of using your variables. Try this:
DoCmd.RunSQL "INSERT INTO tbl (" & FirstField & ", " & SecondField & ") VALUES (Field1, Field2)"

Access 2010 - Cannot edit textbox in unbound form which is populated by recordset

I am using Access 2010 with linked tables from SQL Server 2008. I have a form that I am populating using a recordset and the control source of the textbox in this form is set to a field from the recordset. I find that although I can navigate through all the 16 records on the form, and the form loads correctly, I am unable to edit the Notes text box. It needs to be editable. The textbox has Enabled=True and Locked=False. The AllowEdits property of the form is set to true. All the tables in the query have primary keys. So, is it my query then - since it has right and inner joins in it? So the issue is that I cannot type in the textbox.
Just a little background, I tried using a query as the recordsource for this form, but found that Access' AutoSave feature inserted incomplete records into my Result table, in addition to the updates and inserts done by my Save button event. If the only way to circumvent this is to ask the user whether he/she would like to save changes every time he navigates, then that would be way too frustrating for the end user. So, I have had to use an unbound form where I use VBA to populate it using a ADO recordset.
Incidentally, I can edit the DocID and DocumentType columns, it's the fields from the query that cannot be changed (QCNote)
Here is the code from my Form_Open event. I also have a Form_Current event that disables the Submit button for inapplicable categories.
Private Sub Form_Open(Cancel As Integer)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = CurrentProject.AccessConnection
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
DocID = [Forms]![QCDocAttributes]![DocID]
DocumentType = [Forms]![QCDocAttributes]![Document Type]
strSQL = "SELECT " & DocID & " AS DocID,'" & DocumentType & "' AS DocumentType, QC_QCDecisionPoint.Description, QC_QCDecisionPoint.QCDecisionPointID , QC_QCResultDecisionPoint.QCNote FROM QC_QCResultDecisionPoint RIGHT JOIN ((QC_QCAttribute INNER JOIN QC_QCAttributeDecisionPointAsc ON QC_QCAttribute.QCAttributeID = QC_QCAttributeDecisionPointAsc.QCAttributeID) INNER JOIN QC_QCDecisionPoint ON QC_QCAttributeDecisionPointAsc.QCDecisionPointID = QC_QCDecisionPoint.QCDecisionPointID) ON QC_QCResultDecisionPoint.QCDecisionPointID = QC_QCDecisionPoint.QCDecisionPointID WHERE (((QC_QCAttribute.Description)= '" & [Forms]![QCDocAttributes]![AttributesDropdown] & "' ));"
.Source = strSQL
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End Sub