我有一个奇怪的问题,我的函数在子程序中完美运行,但是当我尝试在单元格中使用它时,它只返回第一个值。预期的功能是与vlookup类似,但是为了给我一个包含所有唯一值的逗号分隔字符串。
我已将其缩小到do
循环。我也尝试使用while
循环重写循环,但结果相同。
Option Explicit
Function vconc(ByVal val_ As String, ByVal rng As Range, ByVal offset_ As Integer) As String
Dim s As String
Dim col_ As Variant
Dim c As Range
Dim firstAddress As String
Set col_ = New Collection
' combination of the .find function and a collection to get a unique list of values
' works similar to a vlookup, but adds all the unique values to a collection
With rng
Set c = .Find(val_, LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
col_.Add c.Offset(0, offset_), CStr(c.Offset(0, offset_).value)
Do
' adding a value with the same key to the collection gives us an error
' but I am interested in a list of unique values, so we simply ignore it
On Error Resume Next
Set c = .FindNext(c)
col_.Add c.Offset(0, offset_).value, CStr(c.Offset(0, offset_).value)
' this debug line only runs if the function is run within a subroutine
Debug.Print c.Offset(0, offset_).value
Loop While Not c Is Nothing And c.Address <> firstAddress
End If
End With
' concatenate the strings, seperate by ,
Dim item_ As Variant
For Each item_ In col_
If s = "" Then
s = item_
Else
s = s & ", " & item_
End If
Next item_
vconc = s
End Function
编辑:根据SJR的建议,我可以通过替换findnext行来解决这个问题
Set c = .FindNext(c)
这一行
Set c = .Find(val_, after:=c, LookIn:=xlValues)