Filter a Listbox based on 2 Combobox(es) - excel

So i'm very new to coding and want to learn how can i filter a listbox based on selection on 2 comboboxes. So what i want to do is when VBA initializes the entire range displays on the listbox and when 1 combobox is selected it filters down the range and when the second combobox is selected it filters down even more and both comboboxes can be used individually. but i couldnt find anything online either for VBA excel or something similar.
Private Sub ComboBox1_Change()
Dim Database(1 To 100, 1 To 4)
Dim my_range As Integer
Dim colum As Byte
On Error Resume Next
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("MASTER")
sh.Range("G5").AutoFilter Field:=7, Criteria1:=Me.ComboBox1.Value
For i = 5 To sh.Range("G100000").End(xlUp).Row
If sh.Cells(i, 1) = Me.ComboBox1 Then
my_range = my_range + 1
For colum = 1 To 5
Database(my_range, colum) = sh.Cells(i, colum)
Next colum
End If
Next i
Me.ListBox1.List = Database
End Sub
Private Sub UserForm_Initialize()
With Me.ComboBox1
.Clear
.AddItem ""
.AddItem "L461"
.AddItem "L462"
.AddItem "L463"
.AddItem "L464"
.AddItem "L465"
End With
End Sub

Related

get conditional lastrow value based on Combox Selected Text

here I have serial number in textbox (txt_Rec) from worksheet("Sale") lastrow.
Now i want to get conditional values (Serial Number) in textbox (txt_Rec), if i select "Sale" from combobox(Me.cmb_Type)dropdown list then i want worksheet("Sale") lastrow serial number in textbox (txt_Rec) and if i select "Purchase" from combobox(cmb_Type)dropdown list then i want worksheet("Purchase") lastrow serial number in textbox (txt_Rec).
Private Sub UserForm_Initialize()
Application.ScreenUpdating = False
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sale")
Dim lastrow As Long
lastrow = Application.WorksheetFunction.CountA(sh.Range("A:A"))
Me.txt_Rec.Value = lastrow
``` dropdown for Item type ```
With Me.cmb_Type
.Clear
.AddItem ""
.AddItem "Sale"
.AddItem "Purchase"
End With
End Sub
Please, copy the next event code in the form code module:
Private Sub cmb_Type_Change()
Dim sh As Worksheet
If cmb_Type.Value <> "" Then
Set sh = ThisWorkbook.Sheets(cmb_Type.Value)
Me.txt_Rec.Text = sh.Range("A" & sh.rows.count).End(xlUp).row
Else
Me.txt_Rec.Text = ""
End If
End Sub
And comment the next code lines from the shown Initialize event:
'Dim lastrow As Long
'lastrow = Application.WorksheetFunction.CountA(sh.Range("A:A"))
'Me.txt_Rec.Value = lastrow
If you want the combo to initially show "Sale", you should add
.ListIndex = 1
after .AddItem "Purchase" and before End With...

Edit filtered listbox

Can anyone help me with a solution or a different method for this? I would like to edit the filtered listbox
I'm trying to get a listbox that is able to display my sheet1 and be able to filter all the blanks/not found in column A. I also want to be able to edit the listbox aswell
I would like my userform2 listbox to display the sheet1 information.
There will also be a checkbox which will filter the listbox to show “not found” or blank lines.
If i double click the selected item on the listbox i would like to edit the information
for userform2
Private Sub ListBox2_Click()
TextBox1.Enabled = True
TextBox1.Value = ListBox2.Value
End Sub
Private Sub TextBox1_Change()
Dim rCell As Range
With ListBox2
Set rCell = Range(.RowSource).Resize(1).Offset(.ListIndex)
rCell.Value = TextBox1.Value
End With
End Sub
Private Sub CheckBox1_Click()
OptimizedMode True
If userform2.CheckBox1.Value = True Then
Worksheets("Table").Range("A1").AutoFilter Field:=1, Criteria1:="Not Found", Operator:=xlOr, Criteria2:="="
userform2.ListBox2.RowSource = vbNullString
userform2.ListBox2.ColumnHeads = False
Dim rng As Range
Dim Cel1 As Range
Dim LR As Long
Dim ws As Worksheet
Set ws = Sheets("Table")
With ws
LR = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A2:A" & LR).SpecialCells(xlCellTypeVisible)
With userform2.ListBox2
.ColumnCount = 1
For Each Cel1 In rng
.AddItem CStr(Cel1.Value)
.List(.ListCount - 1, 1) = Cel1.Offset(0, 1).Value
Next Cel1
End With
End With
End If
If CheckBox1.Value = False Then
With userform2.ListBox2
.RowSource = "Table!A2:A1048576"
End With
End If
OptimizedMode False
End Sub
I've re-designed my code and I believe this will achieve what you are after.
NOTE: This code uses all default object names. You will need to modify it to target the names for your workbook, sheet, useform, controls etc, if you wish to implement into your project.
In designing this answer I used the following:
A new blank Workbook with 1 new Worksheet
A new UserForm (captioned "ListBox Editor") with 1 ListBox that has 2 columns (ColumnCount = 2) and 1 CheckBox (captioned "Show Blanks").
The sample data I used was in Range("A1:A10") filling only odd numbers from row 1. This allows testing for including/excluding blank/empty rows. Screenshots of the Worksheet and UserForm below.
Worksheet data:
UserForms both with and without blanks in the listbox:
All code is written in the code behind module for the UserForm
Most can be written into any other module with calls made to the subs/functions from the UserForm/ListBox events if you'd prefer not to have the working code in the UserForm module.
Code blocks with explanations below (full code block at the end for copy/paste):
Option Explicit
Option Explicit should be included at the top of each and every code module you use. It forces explicit declaration of all variables which helps significantly in avoiding typo's in your code etc.
Private Sub PopulateListBox(ByVal IncludeBlanks As Boolean)
Dim TargetCell As Range
Dim TargetWorksheet As Worksheet
Set TargetWorksheet = ThisWorkbook.Sheets("Sheet1")
With UserForm1.ListBox1
.Clear
For Each TargetCell In TargetWorksheet.Range("A1:A10")
If Not IncludeBlanks Then
If Not TargetCell.Value = "" Then
.AddItem TargetCell.Value
.List(.ListCount - 1, 1) = TargetCell.Row
End If
ElseIf IncludeBlanks Then
.AddItem TargetCell.Value
.List(.ListCount - 1, 1) = TargetCell.Row
End If
Next TargetCell
.ColumnWidths = ";0" 'Hides listbox column that holds row number
End With
End Sub
PopulateListBox is a subroutine I wrote to handle population of the items in the ListBox. It first clears the list, allowing each population of the listbox to be 'refreshed' data. Then it iterates through each TargetCell of the defined Range. If IncludeBlanks is True it has no conditions to meet and adds each cell value into the list, if IncludeBlanks is False it will only add the cell value to the list if the value is not "".
Private Sub CheckBox1_Click()
If Me.CheckBox1.Value = False Then
PopulateListBox False
ElseIf Me.CheckBox1.Value = True Then
PopulateListBox True
End If
End Sub
This _Click event simply updates the ListBox list based on if the CheckBox is checked or not. The CheckBox represents if you are including blanks/empty cells or not so it passes True or False respective to it's Value, to the IncludeBlanks argument in PopulateListBox.
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Dim NewValue As Variant
Dim TargetWorksheet As Worksheet
Set TargetWorksheet = ThisWorkbook.Sheets("Sheet1")
NewValue = InputBox("What is the new value to replace " & UserForm1.ListBox1 & "?")
If Not StrPtr(NewValue) = 0 Then 'Check user did NOT click cancel or [X]
With ListBox1
If NewValue = "" Then NewValue = vbNullString
TargetWorksheet.Cells(.List(.ListIndex, 1), 1).Value = NewValue
.AddItem NewValue, .ListIndex
.RemoveItem .ListIndex
End With
End If
End Sub
The _DblClick Event triggers the code when a list item is double clicked. This code first opens an InputBox to allow the user to enter a new value for the selected listbox item. When the user clicks OK or hit's Enter, the new value is first written to the Cell that the original value came from, then the new value is added as a new list item and finally the previous value is removed. If the user clicks [X] or 'Cancel' the code does nothing.
Private Sub UserForm_Initialize()
PopulateListBox False
End Sub
Much the same as the Checkbox_Change code, this simply populates the ListBox when the UserForm is first initialized. It's written to exclude blanks, specified by False for the IncludeBlanks argument.
Put it all together and you have:
Option Explicit
Private Sub CheckBox1_Click()
If Me.CheckBox1.Value = False Then
PopulateListBox False
ElseIf Me.CheckBox1.Value = True Then
PopulateListBox True
End If
End Sub
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Dim NewValue As Variant
Dim TargetWorksheet As Worksheet
Set TargetWorksheet = ThisWorkbook.Sheets("Sheet1")
NewValue = InputBox("What is the new value to replace " & UserForm1.ListBox1 & "?")
If Not StrPtr(NewValue) = 0 Then 'Check user did NOT click cancel or [X]
With ListBox1
If NewValue = "" Then NewValue = vbNullString
TargetWorksheet.Cells(.List(.ListIndex, 1), 1).Value = NewValue
.AddItem NewValue, .ListIndex
.RemoveItem .ListIndex
End With
End If
End Sub
Private Sub UserForm_Initialize()
PopulateListBox False
End Sub
Private Sub PopulateListBox(ByVal IncludeBlanks As Boolean)
Dim TargetCell As Range
Dim TargetWorksheet As Worksheet
Set TargetWorksheet = ThisWorkbook.Sheets("Sheet1")
With UserForm1.ListBox1
.Clear
For Each TargetCell In Range("A1:A10")
If Not IncludeBlanks Then
If Not TargetCell.Value = "" Then
.AddItem TargetCell.Value
.List(.ListCount - 1, 1) = TargetCell.Row
End If
ElseIf IncludeBlanks Then
.AddItem TargetCell.Value
.List(.ListCount - 1, 1) = TargetCell.Row
End If
Next TargetCell
.ColumnWidths = ";0"
End With
End Sub

Populating a ComboBox with a For loop from the worksheet

I am trying to populate my userform combobox with a list of part numbers after the user has selected the workstation on the previous user form.
My idea was to loop through the column, identify when the string matches the workstation and then add the cell in the column to the right (which turns out to be the product number)
My code looks like this so far:
If station = "MILL" Then
With ComboBox1
.AddItem "350SC109e.1"
.AddItem "350 SC166"
.AddItem "350 SC193"
.AddItem "350 SC195"
End With
End If
If station = "BRAKE" Then
For i = 2 To ws1.Range("A265").End(xlUp).Row
If ws1.Cells(i, 1) = "Brake" Then
ComboBox1.AddItem ws1.Cells(i, 2)
End If
Next i
End If
The MILL is an example of a manually doing the thing I want to accomplish with the loop in the BRAKE if statement.
Here i whipped this up real quick to demonstrate that I could get this to work in a loop. Youll have to adjust to fit your needs though. It did work flawlessly
Private Sub CommandButton1_Click()
Dim txtVal As String
If IsNull(TextBox1.Value) = False Then
txtVal = TextBox1.Value
Else
txtVal = ""
End If
Dim rng As Range
Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A21")
Dim rcell As Range
For Each rcell In rng.Cells
If rcell.Value = txtVal Then
With ComboBox1
.AddItem rcell.Offset(0, 1).Value
End With
End If
Next rcell
End Sub

Search textbox to listbox multi columns

I have a code work perfectly, that search the items in worksheets then the userform textbox display in the listbox. but somehow it show only in one columns in listbox.
I want to show 4 columns in lisbox.
Code:
Private Sub TextBox1_Change()
Dim search As Variant
Dim textbox As Variant
Dim index As Variant
Dim item As Variant
Dim result As Variant
Dim match As Integer
With Me.ListBox1
.RowSource = ""
End With
On Error GoTo skip match = 0 ListBox1.Clear
With Range("Forcast")
Set textbox = .Find(TextBox1, LookIn:=xlValues, lookat:=xlPart)
If Not textbox Is Nothing Then
index = textbox.Address
Do
result = Sheets("Report").Cells(Range(textbox.Address).Row, 1).Value
For Each item In ListBox1.List
If item = result Then match = 1
Next item
If match = 0 Then ListBox1.AddItem result
listbox1.ColumnCount = 4
Set textbox = .FindNext(textbox)
match = 0
Loop While Not textbox Is Nothing And textbox.Address <> index
End If End With
End Sub
2 ways to add items to a ListBox:
Option Explicit
Private Sub UserForm_Initialize()
With ListBox1
.ColumnCount = 4 '---------------------------------------------
'add a 2 dimensional array
.List = Worksheets(1).Range("A1:D3").Value2 '3 rows, 4 columns
'add a 2 dimensional array
.List = Worksheets(1).Range("A1:D1").Value2 '1 rows, 4 columns
.ColumnCount = 1 '---------------------------------------------
'add a 1 dimensional array
.List = Array(1, 2, 3, 4) '4 rows, 1 column
'same as above: '4 rows, 1 column
.AddItem "1"
.AddItem "2"
.AddItem "3"
.AddItem "4"
End With
End Sub

How to bind data from one sheet row till end of the row into combobox using macro

please provide me a solution for this issue.
I am new to macro I am unable to do this operation.
I tried this code
Sub BindCombo()
Dim Last
Last = Sheets("Defect Dump").Cells(2, 2).End(xlDown).Row
With ComboBox1
For Row = 2 To Last
.AddItem Sheets("Defect Dump").Cells(Row, 1)
Next Row
End With
End Sub
But this code shows object error
You need to create an object reference to the ComboBox
try this
Sub BindCombo()
Dim Last As Long, rw As Long
Dim sh As Worksheet
Dim cb As ComboBox
Set sh = Sheets("Defect Dump")
Last = sh.Cells(2, 2).End(xlDown).Row
' get Combobox on "project sheet" sheet
Set cb = Sheets("project sheet").Shapes("ComboBox1").DrawingObject.Object
With cb
.Clear ' remove any existing items
For rw = 2 To Last
.AddItem sh.Cells(rw, 1)
Next
End With
End Sub

Resources