Save record changes - Access ado form - ms-access

Help please!
I've created a database for logging service calls, based on one of Microsoft's templates (Very loosely based now!)
I have a "Case Details" form, which is opened from a case list split form. Originally, this was opening the form with a filter - which I assume means that it is actually loading the whole recordset?
As I assume (hopefully correctly) that this will be quite inefficient as the database grows, I decided to change the form to open and ADO recordset, using a SQL statement, only selecting the record I want.
The code for this is as follows, and the form opens with the correct record, and I can update the fields.
Private Sub Form_Load()
On Error GoTo Form_Load_Err
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
If (IsNull(TempVars!currentid)) Then
Me.DataEntry = True
Else
'Use the ADO connection that Access uses
Set cn = CurrentProject.Connection
'Create an instance of the ADO Recordset class,
'and set its properties
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = "SELECT * FROM Cases WHERE ID = " & TempVars!currentid & ";"
.LockType = adLockOptimistic
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.Open
End With
'Set the form's Recordset property to the ADO recordset
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End If
Call IntializeCollections
Select Case (Me.Status)
Case 7, 8
Call EnableControls(mcolgrpAllFields, False)
End Select
Form_Load_Exit:
Exit Sub
Form_Load_Err:
MsgBox Error$
Resume Form_Load_Exit
End Sub
However, here is the problem. What the blinking heck do I do to save my changes? I've done some googling, and looked at MS Access Form Bound to ADO Disconnected Recordset but I'm still absolutely stumped.
Is there as simple "save the updates" command? or do I have to iterate through each field, check for changes, then save those changes?
Can someone please point me in the right direction?
Thanks in advance

If you need to update one record at a time try this solution for disconnected recordsets: http://www.techrepublic.com/blog/how-do-i/how-do-i-pass-data-over-a-network-using-disconnected-recordsets/

Related

Unable to open ADODB recordset (with password)

I have the below code to open a connection to another Access database and then open a recordset
Sub OpenTest()
Dim Acon As New ADODB.Connection
Dim rst As ADODB.Recordset
With Acon
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "C:\MyFolder\MyDb.accdb"
.Properties("Jet OLEDB:Database Password") = "OpenSesame"
.Open
End With
Set rst = New ADODB.Recordset
rst.Open "SELECT * FROM tblAdmin", Acon, adOpenDynamic, adLockReadOnly
If rst.EOF = False Or rst.BOF = False Then
rst.MoveFirst
Debug.Print rst!UserID
End If
Set rst = Nothing
Acon.Close
End Sub
The connections itself opens fine but then strangely the recordset fails to open and I get a run time error saying
Not a valid password
The password is definitely correct (as evidenced by the connection opening). When setting the password on the database I ensured that the legacy encryption option was selected for compatability. I have also used this code to open a different database and it works fine.
Does anybody have any idea why it may not be working?
For anyone that is interested. I found the problem. It was just because the table I was trying to use in the recordset was actually a linked table. I changed the file path to the one for the back end and it now works fine.
ヾ(`ヘ´)ノ゙

GetRows on a RecordSet won't store text column from Access DB

I've successfully connected to my Access database from excel, and can return the contents of the database in a string Using GetString on my RecordSet. GetString prints all of the contents of the table into a message box as I expect it to(in comments below), but GetRows ignores one of the columns(GCAT in this case), which happens to be the only text field in the database. I am trying to print a particular instance of this field into my excel sheet, but at array position(0,1), where the GCAT field should be, it prints the third item of the record, and not the second as I expect. What am I missing? Does it have something to do with it being a text field? Maybe i'm using the wrong library or database engine? Every other column in the database is returned normally.
Sub Connect()
Dim oConn As ADODB.Connection
Dim oRs As ADODB.Recordset
Dim sConn As String
Dim sSQL As String
Dim arrayString As String
sConn = "Provider='Microsoft.ACE.OLEDB.12.0';Data Source='<path_to_db>'; Persist Security Info='False';"
' Open a connection.
Set oConn = New ADODB.Connection
oConn.ConnectionString = sConn
oConn.Open
' Make a query over the connection.
sSQL = "SELECT ID, GCAT, Min_Years, Max_Years, Contract_Price FROM GCAT"
Set oRs = New ADODB.Recordset
CursorLocation = adUseClient
oRs.Open sSQL, oConn, adOpenStatic, adLockBatchOptimistic, adCmdText
GCATArray = oRs.GetRows()
Sheets("Calculations").Range("D6").Value = GCATArray(0, 1)
'GCATString = oRs.GetString()
'MsgBox GCATString
' Close the connection.
oConn.Close
Set oConn = Nothing
End Sub
This is my first foray in VB so I'm both confused and struggling with the language to being with.
Can't see any obvious faults in your code, have you tried debugging yourself? You can loop the fields in the recordset, and display their names for testing like so:
For i = 0 To oRS.Fields.Count -1
debug.print oRS.Fields(i).Name
Next
That way, you can see whether the field you are looking for is actually there in the first place. Next, you can access the field your're after by doing:
Do While Not oRS.EOF
Debug.Print oRS!GCAT
'Exit Do 'if you want to display only the first, break out of the loop here
oRS.MoveNext
Loop
You don't need the GetRows() in this case, that should give you a performance boost too (very noticible on larger recordsets).

Access VBA recordets - updating a field based on the result of a function that uses other fields as input

I have a simple_table with 4 fields:
a,b,x,P
I am trying to update the field p based on the output of a function that uses the other fields as input parameters. In this case the function is an excel function.
I was using SQL server but really need to access some statistical functions. So yesterday I opened access for the first time. Eeek. I've spent the last day trying to learn vba and following various tutorials on recordsets.
The bit I'm struggling with is how to I update a the P field based on the other fields? In a loop?
Thanks very much.
Dim objExcel As Excel.Application
Set objExcel = CreateObject("Excel.Application")
'Test it works
MsgBox objExcel.Application.BetaDist(0.4, 2, 5)
'OK, that works :)
'set up the ADO stuff
Dim cnn1 As ADODB.Connection
Dim MyRecordSet As New ADODB.Recordset
Set cnn1 = CurrentProject.Connection
MyRecordSet.ActiveConnection = cnn1
'Load data into MyRecordSet
MySQLcmd = "SELECT * FROM simple_table"
MyRecordSet.Open MySQLcmd
'HELP WITH THE NEXT BIT PLEASE!
'Some kind of loop to go through the recordset to set the field P
' equal to the result of the excel function betadist(x,a,b)
'I imagine looping through something like the following semi pseudo code ???
myRecordSet.Fields(“P”).Value = objExcel.Application.BetaDist(myRecordSet.Fields(“x”).Value, myRecordSet.Fields(“a”).Value, myRecordSet.Fields(“b”).Value)
'end of the loop
objExcel.Quit
Set objExcel = Nothing
MyRecordSet.Close
cnn1.Close
Set MyRecordSet = Nothing
Set cnn1 = Nothing
Since your code works with "Dim objExcel As Excel.Application", that means you have a reference set for the Excel object library. In that case, you don't need a full Excel application instance in order to use the BetaDist function. You can set an object variable to Excel.WorksheetFunction and call the function as a method of that object. However, I don't know whether that makes a significant difference. I didn't test the CreateObject("Excel.Application") alternative.
In this sample, I used a DAO recordset instead of ADO. The reason is I've found DAO can be significantly faster with native Access (Jet/ACE) data sources. You can switch to ADO if you prefer, but I don't see an advantage.
Notice I opened the table directly rather than via a query. The DAO dbOpenTable option can also benefit performance.
With those details out of the way, it's just a simple matter of looping through the recordset, calling the function with values from the current row, and storing the function's result in the P field ... pretty much what you outlined in your pseudo-code. :-)
Dim objWFunction As Object ' Excel.WorksheetFunction
Dim MyRecordSet As DAO.Recordset
Dim db As DAO.database
Set objWFunction = Excel.WorksheetFunction ' Excel reference required
Set db = CurrentDb
Set MyRecordSet = db.OpenRecordset("simple_table", dbOpenTable)
With MyRecordSet
Do While Not .EOF
'Debug.Print objWFunction.BetaDist(!x, !a, !b)
.Edit
!p = objWFunction.BetaDist(!x, !a, !b)
.Update
.MoveNext
Loop
.Close
End With
Set MyRecordSet = Nothing
Set db = Nothing
Set objWFunction = Nothing

In Memory, Stand-Alone, Disconnected ADO Recordset

I'm running this code on my datasheet subform when my form loads and I'm not getting any error messages or code breaks. My debug.print shows that the Recordset rs is filled with 2131 records like it should be, but my form shows a single row with #Name? in every field. The control source properties on my controls most certainly do match the field names I have listed above. RS is a form level variable and I'm not closing it or setting it to nothing until the form closes.
Any idea what am I doing wrong?
Set rs = New ADODB.Recordset
rs.Fields.Append "TimesUsed", adInteger
rs.Fields.Append "strWorkType", adVarWChar, 150
rs.Fields.Append "DateLastUsed", adDate
rs.Fields.Append "SelectedYN", adBoolean
Set rs.ActiveConnection = Nothing
rs.CursorLocation = adUseClient
rs.LockType = adLockBatchOptimistic
rs.Open
Dim sSQL As String
sSQL = "MyComplicated SQL Statement Ommitted from this SO Question"
Dim r As DAO.Recordset
Set r = CurrentDb.OpenRecordset(sSQL, dbOpenDynaset, dbSeeChanges)
If Not (r.EOF And r.BOF) Then
r.MoveFirst
Dim fld
Do Until r.EOF = True
rs.AddNew
For Each fld In r.Fields
rs(fld.Name) = r(fld.Name).value
Next
rs.Update
r.MoveNext
Loop
End If
r.Close
Set r = Nothing
Debug.Print rs.RecordCount '2131 records
Set Me.Recordset = rs
OK, so I just read this on the MSDN site:
The recordset must contain one or more fields that are uniquely indexed, such as a table's primary key.
(Note: This information seems to be erroneous in this context.)
is it possible to setup a primary key on a recordset that is only an in-memory object?
Yes, use adFldKeyColumn as the Attrib to the Append Method. Read about FieldAttributeEnum for more details.
If you already have a suitable unique field (or combination of fields) available from your SQL statement, use that. If not, create a long integer field and use it as a fake primary key field ... increment the value for each row you insert.
rs.Fields.Append "pkey", adInteger, , adFldKeyColumn
Also see if this article from Database Journal by Danny Lesandrini is helpful: Create In-Memory ADO Recordsets
I found out that the only way I can make this work is to use LockType adLockPessimistic or adLockOptimisic. adLockReadOnly doesn't work for obvious reasons and for some reason adLockBatchOptimistic does not allow records to display in my form even though the recordset appears to be fully functional.
I also found out that you do not have to have a primary key defined for this type of disconnected Recordset to be bound to a form. I'm sure you won't be able to make any edits or updates to the recordset via the form but in my testing I found that I couldn't make any edits to this type of form/recordset anyway because I was getting Error 3270 (something to do with a missing property). That's really outside the scope of this question.
Here's the minimum amount of code needed to create a working in-memory recordset:
Dim rs As ADODB.Recordset 'Form Level variable
Private Sub Form_Load()
Set rs = New ADODB.Recordset
rs.Fields.Append "ID", adInteger
'Set rs.ActiveConnection = Nothing 'Not Required
'rs.CursorType = adOpenKeyset 'Not Required
'rs.CursorLocation = adUseClient 'Not Required
rs.LockType = adLockPessimistic 'May also use adLockOptimistic
rs.Open
Dim i as Integer
For i = 1 To 10
rs.AddNew
rs("ID").Value = i
rs.Update
Next i
Set Me.Recordset = rs
End Sub
It first appeared to me that binding a form (datasheet view in my case) to this type of disconnected recordset would be a good, simple solution for my particular needs. However, I ran into several problems. The default form sorting does not appear to work when you have your form bound to an ADO recordset. Also, for some reason I never could get this recordset to be editable/updateable which was a requirement for my needs (I was basically using it as a multi-check list). If you obtain the recordset from a table (even if it's an empty table) and then disconnect you can work around this problem. Apparently the table supplies some kind of structure or properties that I've failed to set in my code above, judging by the 3270 error message I get when I try to add/edit a record. And I haven't figured out what those properties are or how to set them.
In conclusion, I think I'll resort to using an Access "temp" table instead since it will be less complicated and not have the problems I've just listed above.
Note: I was able to get everything to work correctly along with inserting new records
by using the example shown above at
Create In-Memory ADO Recordsets
Then changing the following to the forms code...
'Note: The trick was to use rstADO.MoveFirst & rstADO.MoveLast after the rstADO.Update
Option Compare Database
Dim rstADO As ADODB.Recordset
Dim lngRecordID As Long
Private Sub Form_BeforeInsert(Cancel As Integer)
lngRecordID = lngRecordID + 1
rstADO.AddNew
rstADO("EmployeeID").value = lngRecordID
rstADO.Update
rstADO.MoveFirst
rstADO.MoveLast
End Sub
Private Sub Form_Load()
Dim fld As ADODB.Field
Set rstADO = New ADODB.Recordset
With rstADO
.Fields.Append "EmployeeID", adInteger, , adFldKeyColumn
.Fields.Append "FirstName", adVarChar, 10, adFldMayBeNull
.Fields.Append "LastName", adVarChar, 20, adFldMayBeNull
.Fields.Append "Email", adVarChar, 64, adFldMayBeNull
.Fields.Append "Include", adInteger, , adFldMayBeNull
.Fields.Append "Selected", adBoolean, , adFldMayBeNull
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
Set Me.Recordset = rstADO
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set rstADO = Nothing
End Sub

Code To Loop Through and Edit Recordsets

I have found how to loop through recordsets with the following link:
Code to loop through all records in MS Access
However, I want to know if it is possible if I can remove a record from the recordset if it doesn't meet criteria that I specify in the loop.
EDIT
I am now getting an error with the following code:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("fieldHistory", dbOpenTable)
where fieldHistory is the name of the query recordset I want to open. Why am I getting this error? The last line of code there is the source of the error and Access simply states "Invalid operation"
Yes, you can use the DAO recordset's Delete method to delete the current record. This example will delete rows where the fname value is "xxx".
Public Sub DeleteRecordsetRow()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("tblDiscardMe", dbOpenTable)
Do While Not rs.EOF
If rs!fname = "xxx" Then
rs.Delete
'* the next line would trigger *'
'* error 3167: "Record is deleted." *'
''Debug.Print rs!fname
End If
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
Notice that immediately after rs.Delete (i.e. before MoveNext), the deleted row is still "current", but you can't access its values. You can uncomment the Debug.Print line to examine this further.
Edit:
Since your record source is a query rather than a table, try this to narrow down the reason you're getting an error with OpenRecordset.
Public Sub foo20110527a()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("fieldHistory")
If Not (rs.BOF And rs.EOF) Then
rs.MoveLast
MsgBox "RecordCount: " & rs.RecordCount
Else
MsgBox "No records"
End If
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
Since you used English (rather than English-like technical terms), your intent isn't very clear. You ask if you can "...remove a record...", which can mean either that you want to Delete it (in which case you already have a good answer form HansUp), or that you want to filter it out so that you don't see it, while leaving it in the underlying database.
If your intent is the latter (filtering), you have two choices:
Use a SQL statement with a WHERE clause in the original OpenRecordset call.
Use the Recordset's .Filter property before you enter the loop.
Access comes with adequate (if not stellar) Help on either topic.