|
Sub ExtractUniqueValuesToColumnB()
Dim lastRow As Long
Dim uniqueDict As Object
Dim sourceRange As Range
Dim cell As Range
Dim uniqueCount As Long
Dim targetCell As Range
' 初始化字典对象
Set uniqueDict = CreateObject("Scripting.Dictionary")
' 获取A列的最后一个非空单元格的行号
lastRow = ThisWorkbook.Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
' 设置A列的数据范围为源范围
Set sourceRange = ThisWorkbook.Sheets("Sheet1").Range("A1:A" & lastRow)
' 遍历A列的每个单元格,并将唯一值添加到字典中
For Each cell In sourceRange
If Not IsEmpty(cell.Value) Then
' 如果字典中不存在该值,则添加它
If Not uniqueDict.exists(cell.Value) Then
uniqueDict.Add cell.Value, Nothing
End If
End If
Next cell
' 将字典中的唯一值写入B列
uniqueCount = 0
Set targetCell = ThisWorkbook.Sheets("Sheet1").Range("B1")
Dim varKey As Variant
For Each varKey In uniqueDict.keys
targetCell.Offset(uniqueCount, 0).Value = varKey
uniqueCount = uniqueCount + 1
Next varKey
' 清理字典对象
Set uniqueDict = Nothing
End Sub |
|