not able to update access table field using VBA - ms-access

I have a userform in access which submits the data to a table, there are two fields in table which I want to get populated automatically whenever user makes a new entry in form. I am using the below vba code with that form :
Option Compare Database
Public Function GetUserName() As String
Dim obj1 As Object
Set obj1 = CreateObject("WScript.Network")
GetUserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
Set obj1 = Nothing
End Function
Private Sub Form_BeforeInsert(Cancel As Integer)
Owner2 = CreateObject("WScript.Network").UserName
AdvisorName = GetUserName
End Sub
Private Sub Form_Load()
Me.DataForm.Form.Recordset.MoveLast
End Sub
Private Sub SaveBtn_Click()
RunCommand acCmdSaveRecord
Me.Requery
Me.DataForm.Form.Recordset.MoveLast
End Sub
I am able to get the value in "owner" field but not in "AdvisorName" field.
What can be the possible reason behind this ?
is there any mistake in my code or is there any better method of doing this ?

The below code should commit both values to your table using a querydef. This is my preferred approach but there are other ways to do it as well. The qdf represents a sql string that can accept parameters from code. We are inserting the values of our variables directly into the sql string.
I copied the code from the save button to re-establish the form state after entry. This should bring the last record back up, but it will depend on the cursortype of the recordset whether the saved record is represented or not (it might go backwards).
Private Sub Form_BeforeInsert(Cancel As Integer)
Dim qdf As QueryDef
Dim Owner2 As String
Dim AdvisorName As String
Owner2 = CreateObject("WScript.Network").UserName
AdvisorName = GetUserName
Set qdf = CurrentDb.CreateQueryDef("", "INSERT INTO Mau_con (Owner, AdvisorName) VALUES ('" & Owner2 & "', '" & AdvisorName & "')")
qdf.Execute
Me.Requery
Me.DataForm.Form.Recordset.MoveLast
Set qdf = Nothing
End Sub

Related

Setting Combobox Value With VBA MS Access

I am trying to make a module to pass a single result of a query into a Combobox to be populated/displayed immediately on Form_Load event, but I keep getting the following error: Run-time error '2465' "Microsoft Access can't find the field 'MyCombo' referred to in your expression"
Query result is tested and returning the proper value. the problem is in the reference call to the MyCombo combobox.
This is my code below:
Public Function getSetRefNo() As String
Dim rs1 As DAO.Recordset
Dim currentformName As String
currentformName = Screen.ActiveForm.Name
Dim docidrefnoquery As String
Dim dociddefaultvalue As String
Set rs1 = CurrentDb.OpenRecordset("SELECT DISTINCT ColA FROM TblA WHERE ColC = " & Forms(currentformName)![Combo25])
Do Until rs1.EOF = True
docidrefnoquery = rs1(0)
rs1.MoveNext
Loop
rs1.Close
Set rs1 = Nothing
dociddefaultvalue = DLookup("RefNo", docidrefnoquery) 'RefNo here is the target column in the Query
Forms(currentformName)![MyCombo] = dociddefaultvalue 'MyCombo here is the Combobox Name
Debug.Print docidrefnoquery & " - " & dociddefaultvalue
End Function
on the targeted form, I use this code:
Private Sub Form_Load()
Call getSetRefNo
End Sub
after opening the targeted form, I receive the above mentioned error. I don't know what's wrong I tried to trace everything and it seems to be fine, I used the same chunk of codes in other places and worked fine. don't know what's wrong here to be honest. I would be grateful if you could help me elaborate what's going on.
I had to alter the form_load event like the following:
Private Sub Form_Load()
Me.TimerInterval = 30
End Sub
Private Sub Form_Timer()
Me.TimerInterval = 0
Call getSetRefNo
End Sub

MS Access DAO Connection Discard Changes On Exit

So I have this Access form where I use this VBA code with a DAO connection to a MySQL database. Everything works great but if the user closes the form without clicking save button the new record is saved anyway.
So what I'm looking for is if there's any way the on the on close event I can stop the new record being saved to the database?
The code I have,
Private Sub Form_Load()
'Set Form Recordset
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim SQL As String
Set db = OpenDatabase("", False, False, Globales.ConnString)
SQL = "SELECT tbl6Suplidores.ID, tbl6Suplidores.NombreSuplidor, tbl6Suplidores.NumeroComerciante, tbl6Suplidores.DescripcionBienes, tbl6Suplidores.NombreContacto, tbl6Suplidores.NumeroTelefono, tbl6Suplidores.Email " _
& "FROM tbl6Suplidores;"
Set rs = db.OpenRecordset(SQL, dbOpenDynaset, dbAppendOnly)
Set Me.Form.Recordset = rs
End Sub
I'm thinking that since I used the dbAppendOnly it won't let me just delete current record on close event?
Any ideas welcome!
Thanks!
Consider a different approach where you have users enter an unbound form and click a save button to update the MySQL table from populated fields. Exiting form without save will do nothing. This is also a more proactive approach as it allows you to check validation and other logic prior to running save action.
Below uses a parameterized append query with QueryDefs. Also, ID is assumed to be an autonumber and hence left out of query. Sub should be placed behind the OnClick trigger event of save button.
Private Sub SaveButton_Click()
Dim db As DAO.Database, qdef As DAO.QueryDef
Dim SQL As String
Set db = OpenDatabase("", False, False, Globales.ConnString)
' PREPARED STATEMENT WITH NAMED PARAMETERS
SQL = "PARAMETERS ns_param VARCHAR(255), ncom_param INTEGER, db_param VARCHAR(255), " _
& " ncnt_param INTEGER, nt_param INTEGER, e_param VARCHAR(255);" _
& " INSERT INTO (NombreSuplidor, NumeroComerciante, DescripcionBienes, " _
& " NombreContacto, NumeroTelefono, Email) " _
& " VALUES (ns_param, ncom_param, db_param, ncnt_param, nt_param, e_param);"
' INITIALIZE QUERYDEF
Set qdef = db.CreateQueryDef("", SQL)
' BIND PARAMETERS TO FORM FIELDS
qdef!ns_param = Forms!MyFormName!NombreSuplidor
qdef!ncom_param = Forms!MyFormName!NumeroComerciante
qdef!db_param = Forms!MyFormName!DescripcionBienes
qdef!ncnt_param = Forms!MyFormName!NombreContacto
qdef!nt_biens_param = Forms!MyFormName!NumeroTelefono
qdef!e_param = Forms!MyFormName!Email
' RUN ACTION QUERY
qdef.Execute dbFailOnError
Set qdef = Nothing
End Sub

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.

How can I insert records in different columns from multiple textboxes in a MySQL table?

How can I add records from multiple text boxes in a VB.net WinForm, to a remote MySQL database? I want to insert the value in the textboxes (fname, lname) to the corresponding columns in a mySQL table. Only one textbox is visible at a time. The next textbox becomes visible only when the previous one has been submitted. I'm using the following code for entering a single record, but am unable to use it for multiple columns.
Imports MySql.Data.MySqlClient
Public Class Regform
Dim serverstring As String = "server=***;Uid=****;database=****;password=****"
Dim SQLstate As String
Dim firstn As String
Dim SQLconnection As MySqlConnection = New MySqlConnection
Private Sub Regform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SQLconnection.ConnectionString = serverstring
Try
If SQLconnection.State = ConnectionState.Closed Then
SQLconnection.Open()
MsgBox("Connection Established")
Else
SQLconnection.Close()
MsgBox("Connection is Closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
text2.Text = "Well, Hello " & firstn & "Please give me your last name"
End Sub
Public Sub savename(ByRef SQLstatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLstatement
.CommandType = CommandType.Text
.Connection = SQLconnection
.ExecuteNonQuery()
End With
SQLconnection.Close()
MsgBox("Added")
SQLconnection.Dispose()
End Sub
Private Sub cmdsubmit_Click(sender As Object, e As EventArgs) Handles cmdsubmit.Click
SQLstate = "INSERT INTO users(fname) VALUES('" & fname.Text & "')"
savename(SQLstate)
text1.Visible = False
text2.Visible = True
fname.Visible = False
' lname.visible = True
End Sub
Private Sub fname_TextChanged(sender As Object, e As EventArgs) Handles fname.TextChanged
firstn = fname.Text
End Sub
End Class
Can you store the first name in a variable locally until you have the last name? (you already seem to have Dim firstn As String)
firstn = fname.Text
then use something like:
"INSERT INTO users(fname,lname) VALUES('" & firstn & "','" & lname.Text & "')"
If not using this approach or you for this or other reasons want to select back out the ID of inserted rows so that you can update them then use a technique like this:
Return Last ID (IDENTITY) On Insert row VB.NET MySQL
BTW i would not select back out of DB based on first name alone.. they are not very unique ;)
I would not recommend your approach, or rather I may suggest transferring the data from your first form to your second form (assuming they are not on the same form) before submitting the data to the mysql database
create a global declared variable for both forms
Public indform1 As form1
Public indform2 As form2
when you call the form
indform1 = New form1
indform1.Owner = Me
indform1.MdiParent = Me
indform1.Show()
same with form2 - this will allow you to transfer data more easily.
when you create form2 either create a local declared string
dim fname as new string = indform1.fname.text
and use the variable fname to say "hello...."
once they push your submit button for the second form have it run your insert statement
INSERT INTO users(fname,lname) VALUES('" & fname & "','" & lname.Text & "')
or your other option would be to run an update statement after you receive the last name which I would not recommend because as the other responder stated the first name is not very unique unless you add a unique id to it also.
otherwise if it is going to be on the same form and you are only dealing with object visibility - you can use
INSERT INTO users(fname,lname) VALUES('" & fname.text & "','" & lname.Text & "')
making an object visible=false does not modify the content

Can I wrap an Access form with a transaction?

I want to make a form the essentially creates an invoice, but using some other related data as inputs or limits; In the process of adding items to the invoice, I need to reduce the items in another table. Since the user will enter several items at a time, I'd like to issue a "START TRANSACTION" when the form loads, and then do a "COMMIT" when the form updates. Thus, if they cancel the form, the other related tables (shown via subforms) would roll back to the previous values.
Can't be done using bound forms. You could use temporary tables to store the data and then update the main tables. A bit of a kludge but I've done that in the past.
See the TempTables.MDB page at my website which illustrates how to use a temporary MDB in your app.
Yes it can be done, to take control over the transaction in the form you need use this code:
Private Sub Form_Open(Cancel As Integer)
Set Me.Recordset = CurrentDb.OpenRecordset("NAME_OF_YOUR_TABLE_OR_QUERY")
End Sub
After that, you can use DBEngine to control the transaction.
It work for me (Im using Access 2007)
Note: If you insert a new record using the form interface it is visible when the Form_AfterInsert event is raised, therefore you can use DbEngine.Rollback in that event to undo the changes.
I have figured it out its possible to have it on bound forms. Everything you need to assign variable that contain an ID number on change event of any of the parent control. Than you need to transmit that ID value into the subform connected field and perform transaction on both forms the primary and the subform. Here is the example of how I did it.
Primary Form VBA
Option Compare Database
Option Explicit
Private boolFrmDirty As Boolean
Private boolFrmSaved As Boolean
Private Sub EmpolyeesID_Change()
Dim ordID As Integer
Dim subFormOrdID As Object
Set subFormOrdID = Forms!Order.OrderInstallation.Form!OrderID
ordID = Me.Form!OrderID
subFormOrdID.DefaultValue = ordID
End Sub
Private Sub Form_AfterDelConfirm(Status As Integer)
If Me.Saved = False Then Me.Saved = (Status = acDeleteOK)
End Sub
Private Sub Form_AfterUpdate()
Me.Saved = True
End Sub
Private Sub Form_Delete(Cancel As Integer)
If Me.Dirtied = False Then DBEngine.BeginTrans
Me.Dirtied = True
End Sub
'Check if form has got new values in it
Private Sub Form_Dirty(Cancel As Integer)
If Me.Dirtied = False Then DBEngine.BeginTrans
Me.Dirtied = True
End Sub
'Open Form as a Record Set and set the variables for it
Private Sub Form_Open(Cancel As Integer)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM Orders", dbOpenDynaset, dbAppendOnly)
Set Me.Recordset = rs
End Sub
Private Sub Form_Unload(Cancel As Integer)
Dim msg As Integer
If Me.Saved Then
msg = MsgBox("Do you want to commit all changes?", vbYesNoCancel)
Select Case msg
Case vbYes
DBEngine.CommitTrans
Case vbNo
DBEngine.Rollback
Case vbCancel
Cancel = True
End Select
Else
If Me.Dirtied Then DBEngine.Rollback
End If
End Sub
Public Property Get Dirtied() As Boolean
Dirtied = boolFrmDirty
End Property
Public Property Let Dirtied(boolFrmDirtyIn As Boolean)
boolFrmDirty = boolFrmDirtyIn
End Property
Public Property Get Saved() As Boolean
Saved = boolFrmSaved
End Property
Public Property Let Saved(boolFrmSavedIn As Boolean)
boolFrmSaved = boolFrmSavedIn
End Property
Private Sub ProductID_AfterUpdate()
'Calculations of VAT and Floor Price
Dim clcVAT As Integer
Dim sqlQry As String
Dim instID As Integer
instID = Me.Form!ProductID.Value
sqlQry = "SELECT Products.Price FROM Products WHERE Products.ProductID =" & instID & ""
Me.flPrice.RowSource = sqlQry
End Sub
Sub Form VBA
Option Compare Database
Option Explicit
'Transaction for sub-form
Private Sub Form_Open(Cancel As Integer)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM OrderInstallation")
Set Me.Recordset = rs
End Sub
Private Sub Form_AfterUpdate()
Dim emplID As Object
Dim cstmID As Object
Dim prdcID As Object
Dim DataArray As Variant
Dim RqrdFieldErorr As String
Dim qry As String
Set emplID = Me.Parent!EmpolyeesID
Set cstmID = Me.Parent!CustomerID
Set prdcID = Me.Parent!ProductID
If IsNull(emplID.Value) Or IsNull(cstmID.Value) Or IsNull(prdcID.Value) Then
MsgBox ("Please enter select required fields first")
Else
End If
End Sub
'Restrict updates of Installation subform if Employee, Customer and Product is not selected
Private Sub InstallationID_AfterUpdate()
Dim instID As Integer
Dim instPrice As Integer
Dim strQry As String
' Create query based on InstallationID value
instID = InstallationID.Value
strQry = "SELECT Installation.Price, Installation.InstallationID FROM Installation WHERE Installation.InstallationID =" & instID & ""
Me.Price.RowSource = strQry
End Sub