Use variable to SELECT records in a recordset - ms-access

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()

Related

Record Set - No current record

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

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.

Updating text box value from combobox option

I can't work out where I am going wrong with my code. When the user selects a value in the combo box, i want it to go to the Consultants table and grab the default rate for that consultant and stick it in the Hourly Rate text box. This is the msg that I get when I update the combobox.
Private Sub cmbConsultant_Change()
Dim db As Database
Dim rs As DAO.Recordset ''Requires reference to Microsoft DAO x.x Library
Dim strSQL As String
strSQL = "defaultFee * FROM tblConsultants WHERE ID = """ & Me!cmbConsultant & """"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
If rs.RecordCount > 0 Then
Me.txtHourlyRate = rs!CountOfEndDeviceType
Else
Me.txtHourlyRate = ""
End If
Set rs = Nothing
Set db = Nothing
End Sub
You could use DLookup for this - much simpler:
Private Sub cmbConsultant_Change()
Me!txtHourlyRate.Value = DLookup("defaultFee", "tblConsultants", "ID = '" & Me!cmbConsultant.Value & "'")
End Sub
However, most likely your ID is numeric, thus:
Private Sub cmbConsultant_Change()
Me!txtHourlyRate.Value = DLookup("defaultFee", "tblConsultants", "ID = " & Me!cmbConsultant.Value & "")
End Sub
I Think You need some SELECT Here
strSQL = "defaultFee * FROM tblConsultants WHERE ID = """ & Me!cmbConsultant & """"
It Should Be:
strSQL = "SELECT defaultFee AS [CountOfEndDeviceType] FROM tblConsultants WHERE ID = """ & Me!cmbConsultant & """"
Also Note, That [CountOfEndDeviceType] Must be a FieldName, SO I've put it in a Select statement.

combine values from multiple records based on common ID

I've tried many different methods to join the following from;
StockCode Finished_Goods_Codes
100137 2105109
100137 2105110
100137 2105111
To;
StockCode Finished_Goods_Codes
100137 2105109, 2105110, 2105111
My Current Code is as follows;
Public Function ListQuery()
Dim curr As Database
Dim rs As Recordset
Dim SQLCmd As String
Dim productList As String
Set curr = CurrentDb()
SQLCmd = "SELECT Finished_Goods_Codes FROM TEMP_codes WHERE [StockCode] = """ & StockCode & """"
Set rs = curr.OpenRecordset(SQLCmd)
If Not rs.EOF Then
rs.MoveFirst
End If
Do While Not rs.EOF
productList = productList & rs(0) & ", "
rs.MoveNext
Loop
ListQuery = productList
End Function
My Query currently runs the following;
SELECT TEMP_codes.StockCode, ListQuery([Products]) AS [List of Products]
FROM TEMP_codes
GROUP BY TEMP_codes.StockCode;
Could you please help as i'm really stuck on this.
Many Thanks in advance.
Based on the answer given for the question Microsoft Access condense multiple lines in a table, here are the steps:
1 Create the following function
Public Function GetList(SQL As String _
, Optional ColumnDelimeter As String = ", " _
, Optional RowDelimeter As String = vbCrLf) As String
'PURPOSE: to return a combined string from the passed query
'ARGS:
' 1. SQL is a valid Select statement
' 2. ColumnDelimiter is the character(s) that separate each column
' 3. RowDelimiter is the character(s) that separate each row
'RETURN VAL: Concatenated list
'DESIGN NOTES:
'EXAMPLE CALL: =GetList("Select Col1,Col2 From Table1 Where Table1.Key = " & OuterTable.Key)
Const PROCNAME = "GetList"
Const adClipString = 2
Dim oConn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim sResult As String
On Error GoTo ProcErr
Set oConn = CurrentProject.Connection
Set oRS = oConn.Execute(SQL)
sResult = oRS.GetString(adClipString, -1, ColumnDelimeter, RowDelimeter)
If Right(sResult, Len(RowDelimeter)) = RowDelimeter Then
sResult = Mid$(sResult, 1, Len(sResult) - Len(RowDelimeter))
End If
GetList = sResult
oRS.Close
oConn.Close
CleanUp:
Set oRS = Nothing
Set oConn = Nothing
Exit Function
ProcErr:
' insert error handler
Resume CleanUp
End Function
2 Add a Reference for the function in the Module (Tools -> References). Add the Reference Micorosft ActiveX Data Objects 6.1 Library (or the most recent one available).
3 Save the Module with a name different from the function name, say Concatenation
4 Run the following query
SELECT T.StockCode, GetList("Select Finished_Goods_Codes From TEMP_codes As T1 Where T1.StockCode = " & [T].[StockCode],"",", ") AS Finished_Goods_Codes
FROM TEMP_codes AS T
GROUP BY T.StockCode;

Help - VBA - Search Functionality - Database MS access

Database Structure:
UserName String
Location String
Price Number
Requirement:
I have listbox with some items into it say 100. The user will select only 10 randomly in the listbox (after changing the MULTISELECT to 2fmMultiselect property). I will have search button. Once I select and click Search, the total price of selected items has to be calculated and displayed.
My search code ( Thanks to Alex sir)
enter code here
Private Sub CommandButton4_Click()
Dim Cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sName As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set rs = New ADODB.Recordset
sName = Replace$(TextBox1.Text, "'", "''")
rs.Open "Select * from SampleTable where UserName = '" & sName & "'", Cn, adOpenForwardOnly, adLockReadOnly, adCmdText
If (rs.EOF) Then
MsgBox "no match"
Else
TextBox3.Text = rs("UserName") & " " & rs("Location")
rs.Close
End If
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
That code was just to search and display in a textbox.
Now, I need to total the price of what all UserName field selected by the user from listbox.
Try this, but make sure the bound column in your list box is the ID field of your table.
Private Function SelectedListString(lstSelected As Access.ListBox) As String
'Loop though a list and get the IDs of all the selected items
'Assumes the bound column is the contains the ID field
Dim sList As String
Dim vSelected As Variant
With lstSelected
For Each vSelected In .ItemsSelected
sList = sList & .ItemData(vSelected) & ","
Next
End With
If sList <> "" Then sList = Left(sList, Len(sList) - 1) 'trim trailing coma
SelectedListString = sList
End Function
you can use the result in an IN statement in your SQL
Dim sSql As String
If myListbox.ItemsSelected.Count > 0 Then
sSql = "SELECT * FROM table WHERE IDField IN (" & SelectedListString(myListbox) & ")"
End If