Private Sub cmd_ok_Click()
Dim cel As Range
Dim r As Range: Set r = Range("A3:A" & Range("A" & Rows.Count).End(xlUp).Row)
Dim cnt As Integer
Dim avgDays As Double
Dim avgAmt As Double
Dim cust As String
Dim res As String
If Me.chk_Amt Or Me.chk_Days Then 'Check if either is selected, if selected the code returns true
For i = 0 To Me.lb_custList.ListCount - 1 'Loop through listbox to find selected item
If Me.lb_custList.Selected(i) Then
cust = Me.lb_custList.List(i) 'If found, set cust var to value and exit loop
Exit For
End If
Next i
If cust <> vbNullString Then ' check to make sure that cust variable has a value
For Each cel In r 'loop through range
If cel.Value = cust Then 'if it matches cust then
cnt = cnt + 1 'increment count
If Me.chk_Days Then avgDays = avgDays + cel.Offset(, 1).Value 'add days value
If Me.chk_Amt Then avgAmt = avgAmt + cel.Offset(, 2).Value 'add amt value
End If
Next cel
End If
If Me.chk_Days Then res = Round(avgDays / cnt, 2) & " days" 'if days is checked then add avg to res string
If Me.chk_Amt Then 'if amt is checked then
If Len(res) > 0 Then
res = res & vbLf & FormatCurrency(avgAmt / cnt, 2) 'if days was also checked then add a carriage return and the amt avg
Else
res = FormatCurrency(avgAmt / cnt, 2) 'otherwise, just add the amt avg
End If
End If
Else
res = "Nothing Selected"
End If
MsgBox res 'display results
End Sub
Private Sub UserForm_Initialize()
Dim cel As Range
Dim r As Range: Set r = Range("A3:A" & Range("A" & Rows.Count).End(xlUp).Row) 'You can set the range manually, doing it this way makes it dynamic, i.e. you can add rows to your data w/o changing the code
Dim AL As Object: Set AL = CreateObject("System.Collections.ArrayList") 'You need to have some way of not having duplicates, array lists can do this
For Each cel In r
If Not AL.contains(cel.Value) Then 'check if arraylist has cel value
AL.Add cel.Value 'if not, add it to the array list
Me.lb_custList.AddItem cel.Value 'then add it to the listbox
End If
Next cel
End Sub