I am learning how to handle Access VBA recordsets.
In the example below, I am using a SQL query to open my recorset and sort the data using strName col. I can see that the query is working when I am debbuging the code, however I don't know why the table is not getting updated with sorted rows. Any suggestion?
Option Compare Database
Option Explicit
Sub OrderDB()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim mySortedRS As DAO.Recordset
'Set the DAO database to current Access db
Set db = CurrentDb
'Open the table as the recordset
Set rs = db.OpenRecordset("SELECT * FROM Table1 order by strName", dbOpenDynaset)
'Process the rows
Do
Debug.Print rs!strName
rs.Edit
rs.Update
rs.MoveNext
Loop Until rs.EOF
'Cleanup
rs.Close
Set rs = Nothing
End Sub
Related
At the moment, it takes an image I add to my signature folder and puts it straight into the attachments field of my contract. HOWEVER! It does not put it into the specific record for which the button is pressed- it puts the image into the signature box of the first record every time. I am new to SQL, how would I go about making it
So below is my code:
Private Sub Command21_Click()
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset2
Dim strFile As String
Set db = CurrentDb()
strFile = "C:\Users\Reception\Desktop\Files\Signature\sign.png"
Set rs1 = db.OpenRecordset("Table1")
rs1.Edit
Set rs2 = rs1!GuestRegistration.Value
With rs2
.AddNew
!FileData.LoadFromFile strFile
.Update
End With
rs1.Update
Form.Refresh
Set rs2 = Nothing
Set rs1 = Nothing
Set db = Nothing
End Sub
Any help is greatly appreciated!!! Sorry I am so novice.
I tried a few things but I don't understand enough about coding to know what I was doing. I am still a beginner doing this for my business. I just need it to pt the image in the correct record rather than instantly putting it in the first record of the recordset.
Nevermind!! Thank you so much #June7 for the response! I set his response code as a string and referenced it instead of Table1 so it isolates only the record I wanted. Find attached my code below if you need this for help with any projects :)
Private Sub Command21_Click()
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset2
Dim strFile As String
Dim strSQL As String
strSQL = "SELECT * FROM Table1 WHERE ID=" & Me!ID
Set db = CurrentDb()
strFile = "C:\Users\Reception\Desktop\Files\Signature\sign.png"
Set rs1 = db.OpenRecordset(strSQL)
rs1.Edit
Set rs2 = rs1!GuestRegistration.Value
With rs2
.AddNew
!FileData.LoadFromFile strFile
.Update
End With
rs1.Update
Form.Refresh
Set rs2 = Nothing
Set rs1 = Nothing
Set db = Nothing
End Sub
I got following problem I cannot get pass.
I am trying to create recordset in loop. Idea is to add to database some entries related to user selected date ranges in user form. When user selects just one date code works fine but when user selects date ranges it crashes with above runtime error on second loop pass - invalid object or has no values.
Here is my code (part of it in fact, a bit simplified to show the problem):
Dim sql, sql2 As String
Dim x, daty As Integer
Dim dbs As DAO.Database
Set dbs = CurrentDb
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
For x = 0 To 3 '''replaced user selected date ranges with 3 to simplify code
sql = "INSERT INTO tDzialaniaRejestracja (IdSzkolenia, TerminRozpoczecia) VALUES (" & Me.IdSzkolenia & ", '" & Format((Me.DataRozpoczecia + x), "dd.mm.yyyy") & "')"
With dbs
Set qdf = dbs.CreateQueryDef("", sql) '''here i get runtine error 3420 on second loop pass
qdf.Execute dbFailOnError
sql2 = "SELECT ##IDENTITY"
Set rs = .OpenRecordset(sql2, dbOpenDynaset)
lastID = rs.Fields(0)
rs.Close
dbs.Close
End With
Me.IdDzialania = lastID
Me.ProwadzacyFirmaZewn.Value = 23
Set qdf = Nothing
Set rs = Nothing
Next x
Any tips greatly appreciated.
Thank you very much in advance.
regards
I have tried this small piece and it gave me 3420 on the second loop as well.
Sub TestMe()
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb
Dim x As Long
For x = 0 To 3
Set qdf = dbs.CreateQueryDef("", "SELECT * FROM TABELLE1")
dbs.Close
Next x
End Sub
Thus, the problem is that you are closing the dbs in the first iteration and then you are refering against to it.
Don't create a new query for every loop iteration. Just use one query, and use parameters to insert different data.
The real problem, as Vityata pointed out, is that you're closing dbs on the first iteration. I've fixed that as well. But I just couldn't not optimize this code...
Dim sql, sql2 As String
Dim x, daty As Integer
Dim dbs As DAO.Database
Set dbs = CurrentDb
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
sql = "INSERT INTO tDzialaniaRejestracja (IdSzkolenia, TerminRozpoczecia) VALUES (#Param1, #Param2)"
Set qdf = dbs.CreateQueryDef("", sql)
For x = 0 To 3
qdf.Parameters("#Param1") = Me.IdSzkolenia
qdf.Parameters("#Param2") = Format((Me.DataRozpoczecia + x), "dd.mm.yyyy")
With dbs
qdf.Execute dbFailOnError
sql2 = "SELECT ##IDENTITY"
Set rs = .OpenRecordset(sql2, dbOpenDynaset)
lastID = rs.Fields(0)
rs.Close
End With
Me.IdDzialania = lastID
Me.ProwadzacyFirmaZewn.Value = 23
Set rs = Nothing
Next x
'Not necessary, no benefit whatsoever in the following code, but it goes here if you want it
dbs.Close
Set dbs = Nothing
Set qdf = Nothing
This has many additional advantages, such as allowing Access to compile the query only once, simplifying your code, avoiding possible SQL injection, etc.
I have a MS ACCESS query called Query11 that sums up amounts.
Let's say it's got SUM_WEEKLY and SUM_MONTHLY as a field in Query11
In VBA, how could I get each value?
I have tried to get them with the codes below and it did not work.
Dim dbMyDB As Database
Dim rsMyRS As Recordset
Set dbMyDB = CurrentDb
Set rsMyRS = dbMyDB.OpenRecordset("Query11")
MsgBox rsMyRS("SUM_WEEKLY")
MsgBox rsMyRS("SUM_MONTHLY")
Your code should work, and you don't tell the error, but try to be a bit more explicit:
Dim dbMyDB As DAO.Database
Dim rsMyRS As DAO.Recordset
Set dbMyDB = CurrentDb
Set rsMyRS = dbMyDB.OpenRecordset("Query11")
' Check that a record exists.
MsgBox CStr(rsMyRS.RecordCount)
MsgBox rsMyRS("SUM_WEEKLY").Value
MsgBox rsMyRS("SUM_MONTHLY").Value
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("Query11")
' Check a record exists
If rs.RecordCount > 0 Then
MsgBox "SUM_WEEKLY = " & rs!SUM_WEEKLY
MsgBox "SUM_MONTHLY = " & rs!SUM_MONTHLY
Else
MsgBox "Recordset has no records"
End If
I'm trying to find the first record in the table that has my Active Field Name (Boolean) as True (-1).
It goes straight to error on the findfirst line. Please advise.
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("tblinstalments", dbOpenDynaset)
With rs
rs.FindFirst "[Active] = -1"
If rst.NoMatch Then
MsgBox "No entry found"
End If
I'm trying to query a MS Access (2007-2010) database using Excel and print the query to my spreadsheet.
The below code prints only the field header into a specified cell and none of the other data in the selected field. Where am I going wrong? hints etc welcome.
Option Explicit
' Add reference to Microsoft ActiveX Data Objects Lib
Public Sub main(): On Error GoTo Err_handler
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
'open DB connection
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Databaselocation
cn.Open
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
'Query Stuff
rs.ActiveConnection = cn
rs.Open "SQL Query here;"
'does something
Dim fld As ADODB.Field
Dim rng As Range
Set rng = [a2]
For Each fld In rs.Fields
rng.Value = fld.Name
Set rng = rng.Offset(0, 2)
Next fld
Set rng = rng.Offset(2, -rs.Fields.Count)
rng.CopyFromRecordset rs
' closes db connection
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Exit Sub
Err_handler:
MsgBox Err.Description
End Sub
You want to skip over one column at a time when displaying column names, not two, because the rng.CopyFromRecordset method will output the recordset with no gaps.
Set rng = rng.Offset(0, 1)
I tested your code and it does work with that change.
You must loop also in Rows in your rs (ADODB.Recordset) object. Use MoveNext method to move to next row.