如何在VBA中选定的(较大的)范围内计算不同值(数字和字符串混合)的数量?
我是这样想的:
1.将数据读入一维数组。
2.排序数组(快速或合并排序)需要测试哪个
3.如果对数组排序:if(a[i]<>a[i+1]) then counter=counter+1
,只需计算不同值的数量。
这是解决此问题的最有效方法吗?
编辑:我想在Excel中做到这一点。
最佳答案
这是VBA解决方案
您不需要数组即可完成此操作。您也可以使用集合。例子
Sub Samples()
Dim scol As New Collection
With Sheets("Sheet1")
For i = 1 To 100 '<~~ Assuming the range is from A1 to A100
On Error Resume Next
scol.Add .Range("A" & i).Value, Chr(34) & _
.Range("A" & i).Value & Chr(34)
On Error GoTo 0
Next i
End With
Debug.Print scol.Count
'For Each itm In scol
' Debug.Print itm
'Next
End Sub
FOLLOWUP
Sub Samples()
Dim scol As New Collection
Dim MyAr As Variant
With Sheets("Sheet1")
'~~> Select your range in a column here
MyAr = .Range("A1:A10").Value
For i = 1 To UBound(MyAr)
On Error Resume Next
scol.Add MyAr(i, 1), Chr(34) & _
MyAr(i, 1) & Chr(34)
On Error GoTo 0
Next i
End With
Debug.Print scol.Count
'For Each itm In scol
' Debug.Print itm
'Next
End Sub
关于algorithm - 是否在VBA中选择(较大)范围内的不同值的数量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11761723/