I'm trying to write a User Defined Function (UDF) in Excel that will take the values in a range of cells, and concatenate them in a certain way. Specifically, I want to concatenate them in a way that the resulting string could be pasted into a SQL "in" function - i.e. if I have a range in Excel that contains:
apples
oranges
pears
I want the UDF to result in 'apples', 'oranges', 'pears'
(i.e. no comma after the last value).
This is my code - it compiles OK in the VBA window, but when I use it in a worksheet I just get ERROR. Any thoughts much appreciated - I'm a bit of a newbie at writing VBA. And apologies for the vague question; I'm just at a loss to see which bit is causing the trouble.
Function ConcatenateforSQL(ConcatenateRange As Range) As Variant
Dim i As Long
Dim strResult1 As String
Dim strResult2 As String
Dim Separator1 As String
Dim Separator2 As String
Separator1 = "'" 'hopefully the quotes act as escape characters
Separator2 = "',"
On Error GoTo ErrHandler
For i = 1 To CriteriaRange.Count - 1 'all but the last one
strResult1 = strResult1 & Separator1 & ConcatenateRange.Cells(i).Value & Separator2
Next i
'next, sort out the last example in the string
For i = CriteriaRange.Count - 0 To CriteriaRange.Count + 0
strResult2 = strResult1 & Separator1 & ConcatenateRange.Cells(i).Value & Separator1
Next i
ConcatenateforSQL = strResult2
Exit Function
ErrHandler:
ConcatenateforSQL = CVErr(xlErrValue)
End Function