我使用了vba: get unique values from array的eksortso的答案来从数组中获取唯一值
Sub Trial()
Dim myArray() As Variant
Dim i As Long
Dim d As Object
myArray() = Array("Banana", "Apple", "Orange", "Tomato", "Apple", "Lemon", "Lime", "Lime", "Apple")
Set d = CreateObject("Scripting.Dictionary")
For i = LBound(myArray) To UBound(myArray)
d(myArray(i)) = 1
Next i
End Sub
这很好用,但是当我尝试将其应用于某个范围时,从工作表中读取它会给我一个错误-Run-time error '9': Subscript out of range
Sub Clients()
Dim Sht As Worksheet
Dim LastRow As Long
Dim StartCell As Range
Dim ClientType As Variant
Dim UniqueType As Object
Dim i As Long
Set Sht = Worksheets("ALL CLIENTS")
Set StartCell = Range("F6")
'Find Last Row
LastRow = Sht.Cells(Sht.Rows.Count, StartCell.Column).End(xlUp).Row
'Read Client Type Column
ClientType = Sht.Range(StartCell, Sht.Cells(LastRow, StartCell.Column))
Set UniqueType = CreateObject("Scripting.Dictionary")
For i = (LBound(ClientType) - 1) To UBound(ClientType)
UniqueType(ClientType(i)) = 1
Next i
End Sub
是否由于myArray
从下标0
开始而ClientType
从1
开始而发生?我该如何解决?
答案 0 :(得分:1)
是的ClientType
将基于1。
丢掉-1
,还要记住您正在使用2D数组:
For i = LBound(ClientType, 1) To UBound(ClientType, 1)
UniqueType(ClientType(i, 1)) = 1
Next i
列表中只有一个单元格时可能的失败模式,因为在这种情况下,您将不会在ClientType
中获得二维数组
答案 1 :(得分:0)