Hi all,
I'm trying to write some Excel VBA code that when run, displays in a dialogue box, the unique # of values that I currently have selected. This should exclude things not highlighted especially when I am filtered.
Below is the code I have tried but doesn't work right:
<code>
Sub CountUniqueHighlightedCells()
Dim selectedRange As Range
Dim cell As Range
Dim uniqueValues As New Collection
Dim value As Variant
Dim count As Integer
' Check if any cells are selected
If Selection.Cells.Count = 0 Then
MsgBox "No cells selected!", vbExclamation
Exit Sub
End If
' Loop through each selected cell
For Each cell In Selection
' Check if the cell has a background color
If Not cell.Interior.ColorIndex = xlNone Then
' Add cell value to the collection if it's not already there
On Error Resume Next
uniqueValues.Add cell.Value, CStr(cell.Value)
On Error GoTo 0
End If
Next cell
' Count the number of unique values
count = uniqueValues.Count
' Display the count in a dialogue box
MsgBox "Number of unique values in highlighted cells: " & count, vbInformation
End Sub
</code>
Thank you!
Mark
I'm trying to write some Excel VBA code that when run, displays in a dialogue box, the unique # of values that I currently have selected. This should exclude things not highlighted especially when I am filtered.
Below is the code I have tried but doesn't work right:
<code>
Sub CountUniqueHighlightedCells()
Dim selectedRange As Range
Dim cell As Range
Dim uniqueValues As New Collection
Dim value As Variant
Dim count As Integer
' Check if any cells are selected
If Selection.Cells.Count = 0 Then
MsgBox "No cells selected!", vbExclamation
Exit Sub
End If
' Loop through each selected cell
For Each cell In Selection
' Check if the cell has a background color
If Not cell.Interior.ColorIndex = xlNone Then
' Add cell value to the collection if it's not already there
On Error Resume Next
uniqueValues.Add cell.Value, CStr(cell.Value)
On Error GoTo 0
End If
Next cell
' Count the number of unique values
count = uniqueValues.Count
' Display the count in a dialogue box
MsgBox "Number of unique values in highlighted cells: " & count, vbInformation
End Sub
</code>
Thank you!
Mark