Hi all,
I'm working on a macro that will take my selected range (only what I have selected and may or may not be a filtered range) and copy the values to a new sheet and remove duplicates. Here is my code so far, but it's not quite working. it copying things that are filtered out. Any help would be appreciated, thank you!
I'm working on a macro that will take my selected range (only what I have selected and may or may not be a filtered range) and copy the values to a new sheet and remove duplicates. Here is my code so far, but it's not quite working. it copying things that are filtered out. Any help would be appreciated, thank you!
VBA Code:
Sub CopyUniqueValuesToNewSheet()
Dim rng As Range
Dim uniqueValues As Object
Dim cell As Range
Dim newSheet As Worksheet
Dim newRow As Long
' Check if any range is selected
If TypeName(Selection) <> "Range" Then
MsgBox "No range selected!", vbExclamation
Exit Sub
End If
' Set the selected range
Set rng = Selection
' Create a dictionary to store unique values
Set uniqueValues = CreateObject("Scripting.Dictionary")
' Loop through each cell in the range and add unique values to the dictionary
For Each cell In rng
If Not uniqueValues.Exists(cell.value) Then
uniqueValues.Add cell.value, Nothing
End If
Next cell
' Create a new worksheet
Set newSheet = Worksheets.Add
' Initialize the row counter for the new sheet
newRow = 1
' Copy unique values to the new sheet
For Each Key In uniqueValues.keys
newSheet.Cells(newRow, 1).value = Key
newRow = newRow + 1
Next Key
' Autofit columns on the new sheet
newSheet.Columns.AutoFit
' Notify the user
MsgBox "Unique values copied to new sheet successfully!", vbInformation
End Sub