VBA-从动态范围获取唯一值

时间:2018-08-13 20:07:10

标签: excel vba

我使用了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开始而ClientType1开始而发生?我该如何解决?

2 个答案:

答案 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)

enter image description here

function getDataByPath(data, path) {
  for(var i in path.split("/")) data = data[path[i]];
  return data;
}
相关问题