【发布时间】:2020-06-13 22:46:58
【问题描述】:
我使用来自 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?我该如何解决这个问题?
【问题讨论】:
-
问题出在
ClientType = Sht.Range(StartCell, Sht.Cells(LastRow, StartCell.Column))。您的StartCell单元格来自 active 表,但Sht- 来自ALL CLIENTS表。如果ALL CLIENTS工作表不是活动工作表,那么您就有问题了。 -
@JohnyL 感谢您指出这一点