我使用集合來創建獨特的項目。下面是一個例子
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long, i As Long
Dim Col As New Collection, itm As Variant
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To lRow
On Error Resume Next
Col.Add .Range("A" & i).Value, CStr(.Range("A" & i).Value)
On Error GoTo 0
Next i
End With
For Each itm In Col
Debug.Print itm
Next
End Sub
編輯
如果你想要的是收集到數組轉換,那麼你可以添加該代碼註釋
Dim MyAr() As Variant
ReDim MyAr(0 To (Col.Count - 1))
For i = 1 To Col.Count
MyAr(i - 1) = Col.Item(i)
Next
跟進
這是你正在嘗試的嗎?
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long, i As Long
Dim Col As New Collection, itm As Variant
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To lRow
On Error Resume Next
Col.Add .Range("A" & i).Value, CStr(.Range("A" & i).Value)
On Error GoTo 0
Next i
End With
Dim MyAr() As Variant
ReDim MyAr(0 To (Col.Count - 1))
For i = 1 To Col.Count
MyAr(i - 1) = Col.Item(i)
Next
ws.Range("K1").Resize(UBound(MyAr), 1) = Application.Transpose(MyAr)
End Sub
注意:我看到您的查詢解決,但如果我是你,我會使用內置RemoveDuplicates
這是更爲快而短於上述
Columns(1).Copy Columns(11)
Columns(11).RemoveDuplicates Columns:=1, Header:=xlNo
謝謝你的代碼,我可以看到正確的對象正在從'debug.print'填充數組。我也想回發數組到表單,我正在研究'Ws.Range(「K1:K」&Col.Count).Value = MyAr',但我只是得到數組的第一個對象'Col.Count '時間 – xyz
是的,因爲你必須轉置它。更新我的答案,有一刻 –
我有一個問題,雖然......爲什麼這種方法?爲什麼不使用比你試圖實現的更快更短的RemoveDuplicates?看到我最近的編輯。您可能需要刷新頁面 –