I am filtering data using two combo boxes from an excel sheet and updating a listbox. No matter what the results are I always get one blank row in the listbox but the excel data has no blank values or blank rows. Why is this happening? How can I resolve it? Here is the code for filtering and updating the listbox -
VBA Code:
Private Sub FilterData()
Dim Region As String
Dim Type As String
Dim myDB As Range
With Me
If .cmb_Region.ListIndex < 0 Or .cmb_Type.ListIndex < 0 Then Exit Sub
Region = .cmb_Region.Value 'aasign value from respective comboboxes
Type = .cmb_Type.Value
End With
With ActiveWorkbook.Sheets("EMPMaster")
Set myDB = .Range("A1:F1").Resize(.Cells(.Rows.Count, 1).End(xlUp).Row) 'Get data range of all the data
End With
With myDB
.AutoFilter 'remove filters
.AutoFilter Field:=3, Criteria1:=Region
.SpecialCells(xlCellTypeVisible).AutoFilter Field:=6, Criteria1:=Type
Call UpdateListBox(Me.ListBox4, myDB, 1)
.AutoFilter
End With
End Sub
VBA Code:
Sub UpdateListBox(ListBox4 As MSForms.ListBox, myDB As Range, columnToList As Long)
Dim cell As Range, dataValues As Range
If myDB.SpecialCells(xlCellTypeVisible).Count > myDB.Columns.Count Then
Set dataValues = myDB.Resize(myDB.Rows.Count + 1)
ListBox4.Clear ' we clear the listbox before adding new elements
For Each cell In dataValues.Columns(columnToList).SpecialCells(xlCellTypeVisible)
With Me.ListBox4
.AddItem cell.Value
.List(.ListCount - 1, 1) = cell.Offset(0, 1).Value
.List(.ListCount - 1, 2) = cell.Offset(0, 2).Value
.List(.ListCount - 1, 3) = cell.Offset(0, 3).Value
.List(.ListCount - 1, 4) = cell.Offset(0, 4).Value
.List(.ListCount - 1, 5) = cell.Offset(0, 5).Value
.List(.ListCount - 1, 6) = cell.Offset(0, 6).Value
End With
Next cell
Else
ListBox4.Clear ' if no match then clear listbox
End If
ListBox4.SetFocus
End Sub