Hello,
I have a form I developed in Excel 2010 that has a Listview control and is populated from a sheet with 20 columns and 396 rows. I want to have and Index column that gets populated with row numbers at UserForm_Initialize(). The index column populates when I do a search using a combobox, textbox and a command button with the following code, but after working on it all day I cannot find a solution to load the index when the userform initializes. Also I add a column for the index during initialization (code below). Any help would be extremely appreciated.
Private Sub cmbVendorSearch_Click()
' search for part by entering a catagory and a search term
Dim Cnt As Long
Dim Col As Variant
Dim FirstAddx As String
Dim FoundMatch As Range
Dim LastRow As Long
Dim r As Long
Dim StartRow As Long
Dim Wks As Worksheet
'Start in row 2 in sheet 11
StartRow = 2
Set Wks = Sheets(11)
Col = ComboBox1.ListIndex + 1
'If nothing is entered in category box then display message
If Col = 0 Then
MsgBox "Please choose a category."
Exit Sub
End If
' if nothing is entered in search box then display message
If TextBox1.Text = "" Then
MsgBox "Please enter a search term."
TextBox1.SetFocus
Exit Sub
End If
'if user access level is greater than 1, enable listview dblclick function
If frmSearchDatabase.LblAccessLevel.Caption > 1 Then
ListView4.Enabled = True
End If
LastRow = Wks.Cells(Rows.Count, Col).End(xlUp).Row
LastRow = IIf(LastRow < StartRow, StartRow, LastRow)
Set rng = Wks.Range(Wks.Cells(2, Col), Wks.Cells(LastRow, Col))
' Finds a match to text entered in search box - LookAt: x1Whole=exact match, x1Part=Partial Match
If cbVendorMatchText = False Then
Set FoundMatch = rng.Find(What:=TextBox1.Text, _
After:=rng.Cells(1, 1), _
LookAt:=xlPart, _
LookIn:=xlValues, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext)
Else
Set FoundMatch = rng.Find(What:=TextBox1.Text, _
After:=rng.Cells(1, 1), _
LookAt:=xlWhole, _
LookIn:=xlValues, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext)
End If
' Clear listview if nothing is found
If Not FoundMatch Is Nothing Then
FirstAddx = FoundMatch.Address
ListView4.ListItems.Clear
Do 'THIS WORKS BUT ONLY AFTER SEARCH CRITERIA IS RETURNED
Cnt = Cnt + 1
r = FoundMatch.Row
ListView4.ListItems.Add Index:=Cnt, Text:=r
For Col = 1 To 20
Set c = Wks.Cells(r, Col)
ListView4.ListItems(Cnt).ListSubItems.Add Index:=Col, Text:=c.Text
Next Col
Set FoundMatch = rng.FindNext(FoundMatch)
Loop While FoundMatch.Address <> FirstAddx And Not FoundMatch Is Nothing
SearchRecords = Cnt
Else
ListView4.ListItems.Clear
SearchRecords = 0
MsgBox "No match found for " & TextBox1.Text
End If
End Sub
With ListView4
.Gridlines = True
.View = lvwReport
.HideSelection = False
.FullRowSelect = True
.HotTracking = True
.HoverSelection = False
.ColumnHeaders.Add Text:="INDEX", Width:=10
.Sorted = True
.SortOrder = lvwAscending 'will sort Ascending from first column
.Enabled = True
End With
Bookmarks