'RemoveDuplicates' 方法更改选择,不仅是 Range 对象
'RemoveDuplicates' method changes selection, not only Range object
我有一个 Range 对象,它包含来自所选内容的唯一列的数据。我想在此范围对象上使用 RemoveDuplicates
方法以仅获取唯一值。我的问题是:工作表上的选择也被 RemoveDuplicates
方法更改。我只需要更改范围对象。这是我的代码:
Dim rngTst As Excel.Range
Set rngTst = Range(Cells(2, 1), Cells(65000, 1))
With rngTst
.RemoveDuplicates 1, xlYes 'remove duplicated values
End With
我同意对你的问题的所有评论。 Range
对象不太适合您的任务。人们很容易认为某些 Excel 函数可以简单地在宏中重现,但在 VBA 中通常有更好的方法来实现……并避免 Activate
/Select
是认识 VBA 多才多艺的第一步。
如果您只需要遍历唯一值列表并以某种方式处理它们,那么 Collection
对象将是您的理想选择,因为每个键都必须是唯一的,并且远离 Worksheet
对你来说会快得多。
下面的一些代码展示了从 Range
对象中获取值并从中创建一个唯一列表是多么简单。
Dim uniques As Collection
Dim r As Long
Dim v As Variant
'Read the values
With ThisWorkbook.Worksheets("Sheet1") 'adjust to your sheet name
v = .Range(.Cells(2, 1), .Cells(65000, 1)).Value2
End With
'Populate the unique collection
Set uniques = New Collection
On Error Resume Next
For r = 1 To UBound(v, 1)
uniques.Add v(r, 1), CStr(v(r, 1))
Next
On Error GoTo 0
'Loop through your values
For Each v In uniques
'do something with your values
Debug.Print v
Next
我有一个 Range 对象,它包含来自所选内容的唯一列的数据。我想在此范围对象上使用 RemoveDuplicates
方法以仅获取唯一值。我的问题是:工作表上的选择也被 RemoveDuplicates
方法更改。我只需要更改范围对象。这是我的代码:
Dim rngTst As Excel.Range
Set rngTst = Range(Cells(2, 1), Cells(65000, 1))
With rngTst
.RemoveDuplicates 1, xlYes 'remove duplicated values
End With
我同意对你的问题的所有评论。 Range
对象不太适合您的任务。人们很容易认为某些 Excel 函数可以简单地在宏中重现,但在 VBA 中通常有更好的方法来实现……并避免 Activate
/Select
是认识 VBA 多才多艺的第一步。
如果您只需要遍历唯一值列表并以某种方式处理它们,那么 Collection
对象将是您的理想选择,因为每个键都必须是唯一的,并且远离 Worksheet
对你来说会快得多。
下面的一些代码展示了从 Range
对象中获取值并从中创建一个唯一列表是多么简单。
Dim uniques As Collection
Dim r As Long
Dim v As Variant
'Read the values
With ThisWorkbook.Worksheets("Sheet1") 'adjust to your sheet name
v = .Range(.Cells(2, 1), .Cells(65000, 1)).Value2
End With
'Populate the unique collection
Set uniques = New Collection
On Error Resume Next
For r = 1 To UBound(v, 1)
uniques.Add v(r, 1), CStr(v(r, 1))
Next
On Error GoTo 0
'Loop through your values
For Each v In uniques
'do something with your values
Debug.Print v
Next