2016-12-05 7 views
1

私の関数がサブルーチン内で完全に機能するこの奇妙な問題がありますが、セルで使用しようとすると、意図した機能は、vlookupと同様に動作することですが、すべての一意の値を持つカンマで区切られた文字列を私に与えることです。VBA:関数はサブルーチン内で動作しますが、シート内では機能しません

ループを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 

EDIT:私はfindnextのラインにこのライン

Set c = .Find(val_, after:=c, LookIn:=xlValues) 
+2

何らかの理由で、FindNextがUDFで正しく機能しません。 Findを使う必要があります。 – SJR

+0

ハレルヤ!どうもありがとうございます。グーグルではないと思っていたのですが...なぜこれがまだ修正されていないのか... ... – doge

答えて

0

Set c = .FindNext(c) 

を置き換えることによって、この問題を解決することができた後SJRのアドバイス私はその仮想ビールを賭けることができますエラーは、

With rng 
です

ライト:バージョン(モジュール及びシートにおける)の両方において

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

と結果を確認。

+0

残念ながら、私は同じ範囲、$ B:$ B、同じシート名を取得します。提案が来るのを保つ、このことは私をナッツを運転している。 – doge

関連する問題