Record Set - No current record - ms-access

I am having some difficulty with record sets.
CODE:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM tbl_Suggestions_Historic WHERE ID = ' " & ID & " '")
rs.Edit
rs("Status") = "Closed By User"
rs("ReasonClosed") = ClosedWhy
rs.Update
Set rs = Nothing
PROBLEM:
I have a list box with a list of accounts. When an account is click a textbox populates with the record id, I want the changes to update that particular record.
ERROR:
The message received is 'No Current Record'
Any help is appreciated

The likely error is that your ID column is a number, not a string, and thus you should remove the quotes:
Set rs = db.OpenRecordset("SELECT * FROM tbl_Suggestions_Historic WHERE ID = " & ID)
If it is a string, you need to be mindful of your spaces. You're including a space before and a space after the ID.
However, this is a good use case for an update query instead of a recordset. Imo, you should remove all your recordset code, and just use this:
CurrentDb.Execute "UPDATE tbl_Suggestions_Historic SET [Status] = 'Closed By User', [ReasonClosed] = '" & ClosedWhy & "' WHERE ID = " & ID
Or, if you want to do it properly, use parameters. I haven't used them since you didn't
See below for an example using parameters
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.CreateQueryDef("","UPDATE tbl_Suggestions_Historic SET [Status] = 'Closed By User', [ReasonClosed] = ? WHERE ID = ?" )
qdf.Parameters(1) = ClosedWhy
qdf.Parameters(2) = ID
qdf.Execute

Related

String Not Working As Table Name - Access VBA -

The beginning of the following code is supposed to get the BaseName of a file name in a textbox on a form and set it equal to a String "tblnewbid". The Debug.Print tblnew bid prints out the correct Table name exactly as it is supposed to. I verified the characters match exactly and there is an actual table that matches that name.
When I run the code I get error: Cannot find table or constraint. If I manually change tblnew to the actual table name, the code runs fine. Could it be that I need to Dim tblnewbid as something other than string?
Private Sub btnInsertRegions_Click()
DoCmd.Hourglass True ' turn on Hourglass
Dim db As Database
Dim rs As Recordset
Dim strSQL As String
Dim FSO As New FileSystemObject
Dim tblnewbid As String
Set db = CurrentDb
tblnewbid = FSO.GetBaseName(Me.txtFileName)
Debug.Print tblnewbid
db.Execute "ALTER TABLE tblnewbid ADD COLUMN O_StateRegion CHAR", dbFailOnError
db.Execute "ALTER TABLE tblnewbid ADD COLUMN D_StateRegion CHAR", dbFailOnError
Set rs = db.OpenRecordset("Select [OriginState] from [tblnewbid];")
rs.MoveFirst
strSQL = "UPDATE [tblnewbid] INNER JOIN [tblStates]"
strSQL = strSQL & " ON [tblStates].[StateAbbrev] = [tblnewbid].[OriginState]"
strSQL = strSQL & " SET [tblnewbid].[O_StateRegion]=[tblStates].[StateRegion]"
db.Execute (strSQL), dbFailOnError
rs.MoveFirst
strSQL = "UPDATE [tblnewbid] INNER JOIN [tblStates]"
strSQL = strSQL & " ON [tblStates].[StateAbbrev] = [tblnewbid].[DestinationState]"
strSQL = strSQL & " SET [tblnewbid].[D_StateRegion]=[tblStates].[StateRegion]"
db.Execute (strSQL), dbFailOnError
rs.Close
Set rs = Nothing
When you place a variable inside double quotes, it stops being a variable and becomes a literal string.
What you want to do instead is have the variable evaluated and then placed inside of the string. You can do this with concatenation:
ie:
db.Execute "ALTER TABLE " & tblnewbid & " ADD COLUMN O_StateRegion CHAR", dbFailOnError
Apply this concatenation to each line that needs to evaluate your variable.

Use variable to SELECT records in a recordset

I am trying to select records from an Access table using a String variable from the result of a ComboBox selection. I have confirmed the variable (zBEN) contains the correct data when selected. If I manually enter the data in the WHERE part of the statement it works perfectly. If I use zBEN it crashes - I get an error if I don't use the single quotes and I get an empty record set if I use the quotes. The error is 3061, Too few parameters. Expected 1. This error is usually a data type mismatch or incorrect field name.
Private Sub cmdDisplayMembers_Click()
'this displays a record in the dataset - from button click
Dim dbsContacts As DAO.Database
Dim rcdContacts As DAO.Recordset
Dim conArray As Variant 'this is the record array
Dim intArraySize As Integer 'array size
Dim iCtr As Integer 'counter
Dim zBEN As Variant
Dim zName, strSQL As String
zBEN = Me.cbxMembersList
Set dbsContacts = CurrentDb
'this statement works: (and has the combobox value manually entered
strSQL = "SELECT * FROM tblMember_Contact where id_members = '201208FEAR' ORDER BY id_members"
'this statement gives an error 3061, 1:
'strSQL = "SELECT * FROM tblMember_Contact where id_members = zBEN ORDER BY id_members"
'this statement gives an empty record set
'strSQL = "SELECT * FROM tblMember_Contact where id_members = 'zBEN' ORDER BY id_members"
Set rcdContacts = dbsContacts.OpenRecordset(strSQL)
If Not rcdContacts.EOF Then
rcdContacts.MoveFirst 'start the counter at Row #1
intArraySize = rcdContacts.RecordCount
iCtr = 1
ReDim conArray(10)
Do Until rcdContacts.EOF
conArray(iCtr) = rcdContacts.Fields("member_info")
Debug.Print "Item: "; iCtr & " " & conArray(iCtr)
iCtr = iCtr + 1
rcdContacts.MoveNext
Loop
MsgBox ("Error no records")
End If
If IsObject(rcdContacts) Then Set rcdContacts = Nothing
txtCon1 = conArray(1)
txtCon2 = conArray(2)
MsgBox (zBEN)
End Sub
Enclose the criteria in quotes if it's a string. i.e.
strSQL = "SELECT * FROM tblMember_Contact where id_members = '" & zBEN & "' ORDER BY id_members"
You can concatenate the variable's value instead of its name into the SQL statement text as Wayne already suggested:
strSQL = "SELECT * FROM tblMember_Contact where id_members = '" & zBEN & "' ORDER BY id_members"
But if you switch to a parameter query approach, you needn't bother about the quotes:
strSQL = "SELECT * FROM tblMember_Contact where id_members = [which_id] ORDER BY id_members"
Dim qdf As DAO.QueryDef
Set qdf = dbsContacts.CreateQueryDef(vbNullString, strSQL )
qdf.Parameters("which_id").Value = Me!cbxMembersList.Value
Set rcdContacts = qdf.OpenRecordset()

db.OpenRecordset returns something that isn't a recordset; but run as queries they do

I'm trying to generate a bill by route, so I've broken it down by customers belonging to a specific route, and then for each customer totaling their weekly rates to compile a monthly rate.
The problem is, even opening a recordset with a SELECT * IN [table] returns nothing, so there must be some glaring error. Here's my code, I'd be very appreciative if someone could set me straight.
Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim rs3 As DAO.Recordset
Dim custNo As Integer
Dim month_total_v As Integer
Dim weekTotal As Integer
Dim weekStart As Date
Dim sql As String
'sql = "SELECT cust_no FROM Roster WHERE route = Forms![routeBill]![route]"
Set rs = CurrentDb.OpenRecordset("SELECT CUST_NO FROM Roster WHERE ROUTE = 'Forms![routeBill]![route]'")
month_total_v = 0
MsgBox ("Boop.")
If Not (rs.EOF) Then
rs.MoveFirst
Do Until rs.EOF = True
MsgBox ("Boop.")
custNo = rs!CUST_NO
Set rs2 = CurrentDb.OpenRecordset("SELECT wk_rate, wk_strt_dt FROM Roster WHERE wk_strt_dt >= Forms![routeBill]![Text53] AND wk_strt_dt <= Forms![routeBill]![Text4] AND cust_no = custNo")
If Not (rs2.EOF And rs2.BOF) Then
rs2.MoveFirst
Do Until rs2.EOF = True
MsgBox "Boop."
weekStart = WK_STRT_DT
month_total_v = month_total_v + rs2!WK_RATE
Set rs3 = CurrentDb.OpenRecordset("SELECT * FROM monthTotal where cust_no = custNo and billMonth=month(weekStart) and billYear=year(weekStart)") 'specify date ranges to pick from to shorten query
If rs3.EOF Then
sql = "INSERT INTO monthTotal (cust_no, month_total, billMonth, billYear) VALUES (custNo, month_total_v, month(weekStart), year(weekStart))" 'Append, record does not exist
DoCmd.RunSQL sql
Else
sql = "UPDATE monthTotal SET month_total = month_total_v WHERE cust_no = custNo AND billMonth = month(weekStart) AND billYear = year(weekStart)" 'Update, record exists
DoCmd.RunSQL sql
End If
rs2.MoveNext
Loop
Else
'pass
End If
rs.MoveNext
Loop
End If
This query will not return any records when none of the stored ROUTE values contain the literal text, 'Forms![routeBill]![route]' ...
SELECT CUST_NO FROM Roster WHERE ROUTE = 'Forms![routeBill]![route]'
Elsewhere you have a WHERE clause which includes AND cust_no = custNo. But, since custNo is a VBA variable, the db engine doesn't know anything about it and will interpret it to be the name of a parameter for which you haven't supplied a value.
You can avoid those types of problems by using a parameter query in a DAO.QueryDef. Then supply the parameter values (from form controls, VBA variables, whatever ...) and use the QueryDef.OpenRecordset method to load your recordset.
Here is a simple example ...
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSelect As String
strSelect = "SELECT CUST_NO FROM Roster WHERE ROUTE = [which_route]"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strSelect)
qdf.Parameters("which_route").Value = Forms![routeBill]![route]
Set rs = qdf.OpenRecordset
With rs
If .BOF And .EOF Then
MsgBox "no matches found"
Else
.MoveLast
MsgBox .RecordCount & " matches"
End If
.Close
End With
Note the parameter query technique avoids the need to add quotes around text values (and then also cope with text values which may include quotes within them) and format Date/Time values and enclose them within # delimiters.
The problem is here:
FROM Roster WHERE wk_strt_dt >= Forms![routeBill]![Text53] AND wk
You should outquote Forms![routeBill]![Text53]:
FROM Roster WHERE wk_strt_dt >= " & Forms![routeBill]![Text53] & " AND wk
You also need to get the dates right:
WHERE wk_strt_dt >= #" & Format(Forms![routeBill]![Text53], "yyyy\/mm\/dd") & "# AND wk_strt_dt ... etc

how can i fix following VBA code

this code is to populate textboxes in form where sql query is fatching data from table RR_info on the behalf of hr_id. it compare hr_id of rr_info with the bounded value of listbox.
Private Sub Form_Load()
Dim SQL As String
Dim db As Database
Dim rs As DAO.Recordset
SQL = "select * from RR_info where hr_id = " & Forms![hhrrr]![List38] & ";"
Set db = CurrentDb
Set rs = db.OpenRecordset(SQL)
'DoCmd.RunSQL SQL 'at this point it gives me error 2342
Me.RR_ID.value = rs!RR_ID
Me.HR_ID.value = rs!HR_ID
Me.Room_No.value = rs![Room No]
Me.No_of_Beds.value = rs!No_of_Beds
Me.Room_Category.value = rs!Room_Category
Set rs = Nothing
Set db = Nothing
End Sub
You dont need string "DoCmd.RunSQL SQL".
And it is better to use .Value insted of .Text

ms access vba display all fields from a composite key in a form

I am looking for a way to display all fields involved in a composite key in a form field. This is to aid the users when they are entering multiple records to keep track of which they are working on. Currently, Access will only display on field from the Composite key.
On the form, I currently have a look up field to link to the HeaderData table. I want to take the value from that and find and display the associated record in a form field so users will know that they have entered the correct input and do not lose their place during data entry.
Here is what I tried, but I am showing no results:
Private Sub ProviderName_LostFocus()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Dim vcatch As String
strSQL = "SELECT ID, AgencyID, ProviderName, AssessmentPeriod FROM HeaderData"
Set db = CurrentDb
Set rs = db.OpenRecordset("strSQL", dbOpenDynaset)
If Not (rs.BOF And rs.EOF) Then
rs.MoveFirst
Do While Not rs.EOF
If Me.ProviderName.Value = rs.Fields(ProviderName) Then
vcatch = rs.Fields(ID) + " " + rs.Fields(AgencyID) + " " + rs.Fields(ProviderName) + " " + rs.Fields(AssessmentPeriod)
Me.Text22 = vcatch
rs.MoveLast
Else
rs.MoveNext
End If
Loop
Me.Tally1.SetFocus
End If
rs.Close
db.Close
End Sub
I have look all over an cannot find anything about displaying all fields. Any help would be greatly appreciated.
You need to remove the quotes from the first argument to OpenRecordset:
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
Also, you need to surround the rs.fields() argument in quotes:
If Me.ProviderName.Value = rs.Fields("ProviderName") Then
Finally, I would not change the state of the CurrentDb. You found it open, leave it open.
(remove second to last line)
So, cleaning this up a bit:
Private Sub ProviderName_LostFocus()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Dim vcatch As String
strSQL = "SELECT ID, AgencyID, ProviderName, AssessmentPeriod FROM HeaderData"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If Not (rs.BOF And rs.EOF) Then
rs.MoveFirst
Do While Not rs.EOF
If Me.ProviderName.Value = rs.Fields("ProviderName") Then
vcatch = rs.Fields(ID) + " " + rs.Fields(AgencyID) + " " + rs.Fields(ProviderName) + " " + rs.Fields(AssessmentPeriod)
Me.Text22 = vcatch
Exit Do
Else
rs.MoveNext
End If
Loop
rs.close
Me.Tally1.SetFocus
End If
End Sub