【问题标题】:VBA: Function works within subroutine, but not in sheetVBA:函数在子程序中工作,但不在工作表中
【发布时间】:2016-12-05 10:48:32
【问题描述】:

我遇到了一个奇怪的问题,我的函数在子例程中完美运行,但是当我尝试在单元格中使用它时,它只返回第一个值。预期的功能与 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)

【问题讨论】:

  • 由于某种原因 FindNext 在 UDF 中无法正常工作。您必须使用查找。
  • 哈利路亚!非常感谢。没想到谷歌搜索...不知道为什么还没有修复...

标签: vba excel do-loops


【解决方案1】:

我可以打赌虚拟啤酒,错误出在

With rng

写:

debug.print rng.address
debug.print rng.parent.name

在两个版本中(模块和工作表)并检查结果。

【讨论】:

  • 猜得好,但不幸的是我得到了相同的范围,$B:$B,以及相同的工作表名称。不断提出建议,这件事让我发疯了。
猜你喜欢
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-20
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 2016-09-16
相关资源
最近更新 更多