MS Access Retrieve Values from ListBox - vba

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!

Related

Filter as you type combo box me.recordsource

I can upload a file if someone tells me how.
Need help replicating a filter as you type on a combo box that is being used at the record level. Example: Instead of having an open text box for the prefix (e.g. Mr. Mrs. Ms. Dr.), I'm using a combo box that looks up from a reference table. I want to be able to type the letter "r" in the combo box and have it filter out Ms. and showing the remaining values. Once I make a selection store the selected value in the Name table.
Issue: When I add a new value in Combo4 the other rows above clear out if they don't match the value I just typed into the cell. Something likely with the RowSource in the below formula. Do I have something out of sequence or a flawed formula?
What I think I'm trying to do:
1) If Prefix value populated w/ value in t_Name THEN show the matching value in t_ref_Prefix
2) If Combo4 is Blank / Null THEN then open Combo4 and show all values in t_ref_Prefix so a value can be selected.
3) If user is typing text into Combo4 THEN filter on change using * on both sides of the typed value.
Option Compare Database
Option Explicit
Private Sub Combo4_Change()
'https://stackoverflow.com/questions/48133260/display-records-in-access-db-combobox-on-any-text-typed-by-user
'test number of characters entered - if greater then 0 then assign rowsource
If Len(Me.Combo4.Text) > 0 Then
'set the rowsource to match user search criteria
Me.Combo4.RowSource = "SELECT * FROM t_ref_Prefix WHERE Prefix LIKE '*" & Me.Combo4.Text & "*'"
'show the search in real-time
Me.Combo4.Dropdown
Else
'set to no
Me.Combo4.RowSource = "SELECT t_ref_Prefix.auto, t_ref_Prefix.prefix, t_ref_Prefix.sort FROM _
t_ref_Prefix ORDER BY t_ref_Prefix.sort, t_ref_Prefix.prefix"
End If
End Sub
You need to set
Combo4.AutoExpand = False
This will do it.

Determine if an integer is a member of a list of integers

I need to determine if a particular integer does not exists in a datagridview column. I assume I should create an array of the integers from the dgv column, and then compare if the integer exists in the array. However, there is perhaps an easier or simpler way.
I have looked at many articles but none of them resolve my task. Some of the Stack Overflow articles show similar solutions but I can't quite determine what to do.
For a = 0 To Dgv1.RowCount - 1
If Not Dgv1(1, a).Value = Dgv0(1, m).Value Then
Dgv0(1, Dgv0.RowCount - 1).Value = Dgv0(1, m).Value
End If
Next
I hope to compare an integer with a column of integers in a datagridview and if it is present do nothing but if is not present add it to the datagrid view
Are you using wpf? If yes, create a model.
provide a checking mechanism at the setter, use observablecollection or list then bind it to the datagirdview
Get the row and column of the datagridview
then compare (means condtional statement) to the variable you wanna check
and of course it should be inside of loop, loop count is equal to the count of rows you have in the datagridview.
Here's an example code:
Dim column As String = "YourColumnNameHere"
' Assuming 2 is the number you wanna compare
Dim value As Integer = 2
For row As integer = 0 to dataGridView.RowCount - 1
If dataGridView.Rows(row).Cells(column).Value = value Then
' Do something here
Else
' Do something here
End If
Next

If cell is blank then make variable equivalent to any value

I have a workbook with 3 List Boxes. Each List Box is populated by a list that is created, each List Box contains a "Blank" data point. I am trying to write a script that goes:
For lpRows = 1 to 100
For lpColumns = 1 to 8
If ListBox1 = "" and ListBox2 = "Val" And ListBox3 = "Var" Then
Sheets(RndmSheet).Cells(lprows,lpcolumns) = Sheets(DiffSheet).Cells(lprows,lpColumns)
else
end if
However, my code isn't working because VBA is simply searching for a blank cell, where I would prefer it to return any value that contains both ListBox2 and ListBox3, but Listbox1 would be irrelevant.
Is there an easy way to use a wildcard to achieve what I want or will I need to simply make a rather large nested if statements to handle this?
I just added in an if statement
if sheets(rndmsheet).cell(lpRows,lpColumns) = "" then
VarCell = Sheets(rndmsheet).cell(lprows,lpcolumns)
end if
Sorry if that doesn't really make sense.

Excel VBA: Copy the Data up to the last column that has value

The spreadsheet has multiple values in a cell.
What I'm trying to do is get that value found in a cell and paste it to another sheet and copy the other fields(columns) that belong to that value. How do I set the range in order copy the other fields(columns) up to the last column that has value? Thanks in advance.
For iRowGetProdCode = 0 To UBound(sSplitProdCode)
Sheets("Output").Cells(iRowCountOutput, 1).Value = sSplitProdCode(iRowGetProdCode)
iRowCountOutput = iRowCountOutput + 1
Next iRowGetProdCode
here is an idea how to discover an un-empty columns in the same row,
maybe you will find it useful and manipulate it for your needs:
Function LoopUntilLastColumn(ByVal Row As Integer)
Dim i As Integer
i = 1
Do While Cells(Row, i) <> ""
' do somthing
MsgBox (" I AM ALIVE COLUMN!")
i = i + 1
Loop
' you can also use the return value of the function.
LoopUntilLastColumn = i
End Function
I'm not exactly sure about what you're asking, but here are my three best guesses.
1.) Splitting delimited data from a single cell to columns
Without VBA: Use the "Text to Columns" function (Excel Ribbon:
Data|Data Tools).
With VBA: Use the split function MSDN (Related Post), then assign array values to target cells. Or parse your string manually with a loop.
2.) Finding the end of a continuous range
Without VBA: Use ctrl + arrow key
With VBA: Use the Range.End Property
3.) Looping through columns and rows
Used a nested loop:
For c = 1 to 5
For r = 1 to 20
Cells(r,c) = "Row = " & r & ", Column = " & C
Next
Next
Editing Suggestions (I don't have enough reputation to directly comment or edit)
This question as worded may be too specific for StackOverflow. Consider re-wording so that the problem can be understood in a general context and your question can be more useful to others.
Also, the wording is a little confusing. For example, use of the term "value" seems to change from referring to delimited data to referring to cell content in VBA. Likewise, it can be confusing to use "fields" or "columns" to describe the data if it's actually delimited text, so clarity on the data's state of existence would help.
It also seems to me that you've parsed the string on it's delimiter to an array, and that you're looping through this array to write the data in rows. I still can't see how exactly your question about setting a range fits in.

Is there a way to check for duplicate values in Excel WITHOUT using the CountIf function?

A lot of the solutions here on SO involve using CountIf to find duplicates. When I have a list of 100,000+ values however, it will often take minutes for CountIf to search for duplicates.
Is there a quicker way to search for duplicates within an Excel column WITHOUT using CountIf?
Thanks!
EDIT #1:
After reading the comments and replies I realize I need to go into greater detail. Let's pretend I'm a birdwatcher, and after I return from a birdwatching trip I input anywhere from 1 to 25 or 50 new birds that I saw on my trip into my "Master List of Birds Seen". This is really a dynamically growing list, and with each addition I want to make sure I'm not duplicating something that already exists in my list.
So, in column A of my file are the names of the birds. Column B-M might contain other attributes of the birds. I want to know if a bird that I just added in column A after my latest birdwatching trip ALREADY exists somewhere ELSE in my list. And, if it does, I would manually merge the data of the 2 entries and throw away some and keep some after careful review. I clearly don't want to have duplicate entries of the same bird in my database.
So, ultimately I want some indication that there is or isn't a duplicate somewhere else, and if there is duplicate please tell me what row to look in (or highlight or color both of the duplicates).
The fastest way that I know of (in case you are using Excel 2007/2010/2011) is to use Data (In Ribbon) | Remove Duplicates to find the total number of duplicates OR to remove duplicates. You might want to move data to a temp sheet before you test this.
The 2nd fastest way is to use Countif. Now Countif can be used in many ways to find duplicates. Here are two main ways.
1) Inserting a New Column next to the data and putting the formula and simply copying it down.
2) Using Countif in Conditional formatting to highlight cells which are duplicates. For more details, please see this link.
suggestions for a macro to find duplicates in a SINGLE column
EDIT:
My Apologies :)
Countif is the 3rd fastest way!
The 2nd fastest way is to use Pivot Tables ;)
What exactly is your main purpose of finding duplicates? Do you want to delete them? Or Do you want to highlight them? Or something else?
FOLLOWUP
Seems like I made a typo in the formula. Yes for large number of rows, CountIf does take minutes as you suggested.
Let me see if I can come up with a VBA code to suit your exact needs.
Sid
You can use VBA - the following function returns a list of unique entries within a list of 100,000 in less than a second. Usage: select a range, type the formula (=getUniqueListFromRange(YourRange)) and validate with CTRL+SHIFT+ENTER.
Public Function getUniqueListFromRange(parRange As Range) As Variant
' Returns a (1 to n,1 to 1) array with all the values without duplicates
Dim i As Long
Dim j As Long
Dim locKey As Variant
Dim locData As Variant
Dim locUniqueDict As Variant
Dim locUniqueList As Variant
On Error GoTo error_handler
locData = Intersect(parRange.Parent.UsedRange, parRange)
Set locUniqueDict = CreateObject("Scripting.Dictionary")
On Error Resume Next
For i = 1 To UBound(locData, 1)
For j = 1 To UBound(locData, 2)
locKey = UCase(locData(i, j))
If locKey <> "" Then locUniqueDict.Add locKey, locData(i, j)
Next j
Next i
If locUniqueDict.Count > 0 Then
ReDim locUniqueList(1 To locUniqueDict.Count, 1 To 1) As Variant
i = 1
For Each locKey In locUniqueDict
locUniqueList(i, 1) = locUniqueDict(locKey)
i = i + 1
Next
getUniqueListFromRange = locUniqueList
End If
error_handler: 'Empty range
End Function
If using Excel 2007 or later (which is likely from the 100,000+ values) you can choose:
Home Tab | Conditional Formatting > Highlight Cell Rules > Duplicate Values...
Right-click a highlighted cell and filter by selected cell color to show just the duplicates (be aware however this can be slow with conditional formatting).
Alternatively run this code and filter for colored cells which takes only a second on 100,000 cells:
Sub HighlightDupes()
Dim i As Long, dic As Variant, v As Variant
Application.ScreenUpdating = False
Set dic = CreateObject("Scripting.Dictionary")
i = 1
For Each v In Selection.Value2
If dic.exists(v) Then dic(v) = "" Else dic.Add v, i
i = i + 1
Next v
Selection.Font.Color = 255
For Each v In dic
If dic(v) <> "" Then Selection(dic(v)).Font.Color = 0
Next v
End Sub
Addendum:
To select only duplicate values without code or formulas, i have found this method useful:
Data Tab | Advanced Filter... Filter in Place, Unique Records Only, OK.
Now select the range of unique values and press Alt+; (Goto Special... Visible cells only). With this selection clear the filter and you will see that all unselected cells are duplicates, you can then press Ctrl+9 (Hide Rows) to show just the duplicates. These rows can be copied to another sheet if needed or marked with an "X".
You do not mention what you want to do when you find them. If you merely want to see where they are...
Sub HighLightCells()
ActiveSheet.UsedRange.Cells.FormatConditions.Delete
ActiveSheet.UsedRange.Cells.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, Formula1:=ActiveCell
ActiveSheet.UsedRange.Cells.FormatConditions(1).Interior.ColorIndex = 4
End Sub
Preventing Duplicates with Data Validation
You can use Data Validation to prevent you entering duplicate bird names. See Debra Dalgelish's site here
Handling existing duplicates
My free Duplicate Master addin will let you
Select
Colour
List
Delete
duplicates.
But more importantly it will let you run more complex matching than exact strings, ie
Case Insensitive / Case Sensitive searches (sample below)
Trim/Clean data
Remove all blank spaces (including CHAR(160)) see the " mapgie" and "magpie" example below
Run regular expression matches (for example the sample below replaces s$ with "" to remove plurals)
Match on any combination of columns (ie Column A, all columns, Column A&B etc)
I'm surprised that no one has mentioned the RemoveDuplicates method.
ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1
This will simply remove any duplicate entries on the active worksheet in column A. It takes milliseconds to run (tested with 200k rows). Mind you, this will strictly delete all the duplicate entries. Although that isn't how the original question was worded, I do believe that this still serves your purpose.
One simple way of finding unique values is to use the advance filter and filter for unique values only and copy and paste them into other sheet as when the pivot is removed you will get the whole data with the duplicate in them.
Sort the range
and in next column put `=if(a2=a1;1;if(a2=a3;1;0))
"1" will be displayed for duplicates.