How to get Access Report textbox to concatenate records from a table when the report is generated from a form? - sql

Essentially this includes 3 components.
First is a form, here the user, via a listbox, chooses multiple names.
For example, they highlight the following names.
Jane
John
Bob
They click a button called "btnGenerate" and these three names get entered as seperate records into a table called "NameCriteria" like this:
ID Name
1 Jane
2 John
3 Bob
Along with this, on-click of the button btnGenerate, a report is generated.
What I cannot seem to get working is that on the report, I hope to get a summary of what was selected on the form. I have a textbox on this report which I am trying to get to generate the following result
Jane, John, Bob
OR if there is only one name highlighted when the btnGenerate is clicked, the textbox will only display
Jane
I cannot seem to get this working. In the report, on the textbox, under the textbox's data/control source, I have entered the following code.
=[Forms]![Report]![lstName]
This just leaves the textbox blank. I have also tried referencing the table "NameCriteria" using
=[Table]![NameCriteria]![Name]
and I return #Error in the textbox.

I'd use something along these lines, using ADO, but its been a long day, so there may be simpler solution.
Public Function CONCAT_SQL(strSQL As String) As String
Dim r As ADODB.Recordset
Dim a As Variant
Set r = New ADODB.Recordset
r.Open strSQL, CurrentProject.Connection, 1
a = Split(r.GetString, Chr(13))
ReDim Preserve a(UBound(a) - 1)
CONCAT_SQL = Join(a, ",")
End Function
Called like so,
me.textbox1.value = CONCAT_SQL("Select [Name] from [NameCriteria]")

Related

MS Access Retrieve Values from ListBox

UPDATE: 3/20/2019
After subthread conversation (below), I renamed the ListBox. ItemsSelected property WORKS. Value still returning NULL int he code
This is my first time dealing with multi-select lists in Access. I have a report form with some dropdowns, checkboxes, and a listbox. The listbox contains almost 70 items - Let's call them "Cities".
The ListBox allows multiple selections. In VBA, I'm taking each of the parameters - from the other controls on the form, to create a giant WHERE condition that feeds my report.
The problem is that Access is not reading the values selected from the ListBox. When I step through that line of code, the value is NULL.
So far:
Dim s As Variant
s = Me.City.Value & ""
This is where I know I wrong-turned, but, not having dealt with a multi-select ListBox before, I don't know the syntax to get the values read.
Next: Check for whether or not values are selected in List "s":
If s <> "" Then
Check for other parameters in the current WHERE condition. IF none exist, THEN
If c.WhereCondition = "" Then
c.WhereCondition =
Set WHERE Condition by comparing List values (which are Strings) to the Yes/No values of equivalent fields in Source table.
I have to compare the List values to the 70 fields in the table - to pull out those records that match.
No, there's not 1 field - say Cities, with 70 possible values. Instead, each of the 70 possible Cities is its own Yes/No field. I inherited this DB. It's how it was built.
Currently, my attempt at this looks like:
c.WhereCondition = "( City1 = -1 OR City2 = -1 OR City3 = -1 OR .....)
`IF there are parameters in the current WHERE clause, THEN compare values in List to Source table, AND APPEND result to WHERE condition with "AND"
ELSE
c.WhereCondition = c.WhereCondition & " AND (City1 = -1 OR City2 = -1, OR ...)
End If
End If
I hope I was able to explain this well enough. The 1st problem is getting the values read. I won't know if my attempt at comparison is right or wrong without that.
THIS took a LOT of breadcrumbs to get me here!
Solution:
Dim s As Variant
Dim i As Integer
Dim ctl As Control
Set ctl = Me.Counties
If ctl.ItemsSelected.Count <> 0 Then
For Each s In ctl.ItemsSelected
t.WhereCondition = ctl.ItemData(s) & " = -1"
Next s
End If
I had to rename the control from County to Counties. Looks like the former was part of the report, and screwing everything else up. I did this after initially deleting & re-adding the control.
The comments here really helped. I just needed to figure out how to work with the properties in order to get what I wanted.
I have to compare 70 yes/no fields to the data, pulling out only those that return True. Hence the -1.
It compiles. It runs. Fingers crossed for data accuracy.
Thanks!

How to iterate display values in a combobox

I have a combobox whose values (displayvalue) are formatted (from a database query):
John Doe (11111)
where 11111 is the userID. The UserID is the login name for their machine and I want to default the selected value to the login UserID.
Since combobox.findstring(UserID) only matches if the entry begins with that string, I need to iterate through the values to look for the substring of UserID in the entries.
I've searched around here, but solutions seems to land all around this specific example. I can't seem to find a method that returns the display value at a specific index. What am I missing?
EDIT:
This is how I am populating my combobox:
Private Sub PopulateDropdown(strSQl As String, objControl As ComboBox, strTextField As String, strDataField As String)
Dim objdatareader As New DataTable
objdatareader = DataAccess.GetDataTable(strSQl)
objControl.DataSource = objdatareader
objControl.DisplayMember = strTextField
objControl.ValueMember = strDataField
End Sub
This may actually help folks trying to find the ValueMember of a combobox as well.
I am populating my combobox from a datatable, so this solution may only be valid from that. I am not really sure why this works. I just stumbled upon it.
First, I started by doing a for each item in combobox.items. According to intelisense, there is no property of .value, .text, .DisplayMember, or anything related to that. I did notice that the return type on combobox.items is a DataRowView. I am not sure why that is, but I went with it. One of the members of DataRowView is Row. It turns out, each column from the DataTable is added to the Row collection in 'item's' DataRowView. Rows(0) is the first column, Row(1) is the second, etc. I was then able to look in the Row's full text to find my userid, and then select that row by using the FindExactString of the combobox. The below code works (I built the datatable manually in this example):
dim UserID As String="12345"
dim MyTable as New Datatable
MyTable.Columns.Add("Value", Type.GetType("System.String"))
MyTable.Columns.Add("Text", Type.GetType("System.String"))
MyTable.rows.add("1","Bob Smith(11223)"
MyTable.rows.add("2","George Brown(12345)"
cboAssignedID.datasource=MyTable
cboAssignedID.DisplayMember="Text"
cboAssignedID.ValueMember="Value"
For Each item In cboAssignedID.Items
If InStr(item.Row(1).ToString, UserID) > 0 Then
cboAssignedID.SelectedIndex = cboAssignedID.FindStringExact(item.Row(1).ToString)
End If
Next

VBA - Based on User Input - look up value in table

I have created a form that asks for two user inputs, site location and sku. Site location is a drop down and SKU is a text box. Below it there is a textbox which I want to populate based on user input after they hit the "whats my price?" button.user form
I have a matrix of prices with the SKU in column B and the sites across the top in row 1 with their respective prices in the matrix(columns D-H). I have attached a sample of the table. Please note that the "SKU" and "Site" titles will not be in my actual matrix.
pricing table
I need assistance coding the "What's my price?" button in the user form.
I feel as though I would need an if statement using some sort of look up but i'm a little lost as to how to start the code.
Here is what you have to do:
Read the value from the site field;
Read the value from the SKU field;
Display the matching in the Your Price is field, using the following formula:
WorksheetFunction.Index(Range,site field, sku field)
More about WorksheetFunction.Index here:
https://msdn.microsoft.com/en-us/library/office/ff197581.aspx
You need to use Application.Match on the row and the column independently, then get the corresponding cell. Try the following code, but replace the control's names (txtSku, cmbSite) and the sheet's code name (mySheet) with yours.
Sub WhatsMyPrice_Click()
Dim rowNum, colNum
rowNum = Application.Match(txtSku.Value, MySheet.Range("B:B"), 0)
If IsError(rowNum) Then MsgBox "SKU not found": Exit Sub
colNum = Application.Match(cmbSite.Value, MySheet.Rows(2), 0)
If IsError(rowNum) Then MsgBox "Site not found": Exit Sub
txtPrice.Value = MySheet.Cells(rowNum, colNum).Value2
End Sub

How to autocomplete a line with data suggestion?

Context:
In my company, some assistants fill out an Excel table, which is a users list (First Names, Last name, ID number). After, I use this list with a PowerShell script. But very often the users list is not correctly completed. For example, assistants forget to input ID number... .So i would like help assitants to fill this Excel with data suggestions/autocomplete.
Technical:
In the "Data" sheet, I have all data possible (First Names, Last name, ID number).
With the "Name Manager" I created:
d_FirstName to select the first cell
c_FirstName to select all column,
l_FirstName to apply function: =OFSSET(d_FirstName;0;0;COUNTA(c_FirstName)-1;1)
In "Form" sheet, I created drop-down list with function: =IF(A1<>"";OFSSET(d_FirstName;MATCH(A1&"*";l_FirstName;0)-1;;SUMPRODUCT((MID(l_FirstName;1;LEN(A1))=TEXT(A1;"0"))*1));l_FirstName)
So, when the user types a letter, the drop down list "suggest" a correct FirstName.
Question:
How to adapt the last query, to complete a line with First Name and Last name and ID number corresponding if user type only First Name ?
For example:
If user select a First Name in drop down list, Excel complete the lign with Last name and ID number corresponding .
If user select a ID number in drop down list, Excel complete the lign with Last name and First Name corresponding.
In second time, how to show dropdown list automatically when user type one letter ?
Thank you
You can accomplish this using the combobox's properties and change event. The combobox will take a 1 or 2 dimensional named range or a formula that returns a range as it's RowSource. Here I have the text column set to the 3rd column.
Private Sub cboEmpID_Change()
With cboEmpID
If Not IsNull(.Value) Then
lblEmployee.Caption = .List(.ListIndex, 1) & ", " & .List(.ListIndex, 0)
End If
End With
End Sub
Private Sub UserForm_Initialize()
Dim ColumnWidths As String
With Worksheets("Sheet1")
ColumnWidths = .Columns(1).Width & ";" & .Columns(2).Width & ";" & .Columns(3).Width
End With
With cboEmpID
.ColumnHeads = True
.ColumnCount = 3
.ColumnWidths = ColumnWidths
.TextColumn = 3
.ListWidth = Range("Sheet1!A:C").Width
.RowSource = "OFFSET(Sheet1!$A$1,1,0,COUNTA(Sheet1!$A:$A)-1,3)"
End With
End Sub
You need making a cascading dependent Excel drop down list.See

Access textbox with multiple values to query

I have an Access database, where I have a form with a textbox (named c1) and a button. When I click the button it opens a datasheet form with information filtered by the textbox value.
The button vba looks like this:
c1.Value = Replace(c1.Value, ",", " Or ")
DoCmd.OpenForm ("dsForm")
The query behind the datasheet looks something like this in design view:
Field: Name1 | Name2
Criteria: | Like [Forms]![Menu]![c1].[value]
This is so I could later export the results of this query to excel.
So my issue is that I want to enter values into the textbox and separate them with a comma, which would be later turner into an Or by vba. Why I'm doing this with 1 textbox not multiple, is because I could have many values that I want to search by.
Right now it works if I enter one value into the textbox, but when I enter 2 values it's not working. I'm pretty sure that the query is taking the whole statement as a string for example if I enter 110,220 it's supposed to be Like "110" or "220", but on the query it would be Like "110 or 220".
I've tried by setting the field to be either a string or a number as well. How would I manipulate the criteria on a query from vba?
I recommend writing a SQL string with the IN statement instead of the OR, and using the OpenArgs event to pass data from the main form over to the datasheet form.
Main Form Button Code
Dim sql as String
sql = "Select * From [table name] Where Name2 IN (" & c1 & ")"
DoCmd.OpenForm "dsForm", acFormDS, , , , , sql
Datasheet form (dsForm) Code -- Use the Form_Load event.
Private Sub Form_Load()
Me.RecordSource = Me.OpenArgs
End Sub
The IN statement allows you to use commas. The OpenArgs event allows you to pass values from one form over to another.
Actually my first method was terrible, read the values into an array like this:
Sub y()
a = "a,b,c,d"
'Split into 1d Array
b = Split(a, ",", , vbTextCompare)
For c = 0 To UBound(b)
Debug.Print b(c)
Next c
End Sub
You can loop through the array as in the debug.print loop and use each value separately.