所以我正在尝试创建一个能够获得范围内所有唯一值的函数,我是新的vba,所以我尝试了但是它没有工作(#VALUE) 。我最终希望数组中的每个值都输出到它下面的一个单元格。
这是我写的代码
Option Explicit
Function getUnique(dataSet As Range, Column As String)
Dim data() As String
Dim dataSize As Integer
Dim dictionary As Object
Dim i As Long
dataSize = dataSet.Rows.Count
Set dictionary = CreateObject("Scripting.Dictionary")
ReDim data(dataSize)
For i = 1 To UBound(data)
data(i) = dataSet(Column & i).Value
dictionary(data(i)) = 1
Next i
Dim v As Variant
For Each v In dictionary.Keys()
Debug.Print dictionary.Keys
Next v
答案 0 :(得分:2)
您的代码可以使用一些更改,如下所示:
Function getUnique(dataSet As Range) '<<< remove Column
Dim data() As String
Dim dataSize As Integer
Dim dictionary As Object
Dim i As Long
dataSize = dataSet.Rows.Count
Set dictionary = CreateObject("Scripting.Dictionary")
ReDim data(dataSize)
For i = 1 To UBound(data)
data(i) = dataSet.Cells(i, 1).Value '<<< using Cells
dictionary(data(i)) = 1
Next i
Dim v As Variant
For Each v In dictionary.Keys()
Debug.Print v '<<<
Next v
End Function
但是,如果您尝试在Worksheet单元格中使用此函数,则在尝试将值放入其他单元格时,它将无法工作。用户定义的函数不能像那样工作,您必须将它设为Sub并在单击按钮或其他事件时运行它。