错误#VALUE,VBA中的UDF中包含长字符串,用于Excel

时间:2015-12-11 14:45:41

标签: string excel vba excel-vba excel-udf

我使用下面的UDF连接引用以包含结果 像ref in ('ref1', 'ref2', ...)这样的SQL查询。

UDF 正常工作,但是当我需要输入一个巨大的参考列表时,  我在Excel中获得#VALUE

我已经看过 this answer ,但我无法让我的UDF工作......

我尝试将功能类型从String更改为Variant(明确地),
 但它并没有改变一件事......

我还尝试了ConcatSQL2 = A(0)ConcatSQL2 = A作为输出 Dim A(0 To 0) As String声明,......再次说它不起作用......  我的想法已经不多了......

有关信息,结果字符串预计长约220k ...
为了帮助您生成大量文本,您可以使用Lorem Ipsum generator here!

Public Function ConcatSQL2(Plage As Range, Optional Doublon As Boolean = True)
Dim A() As String, _
    Cel As Range
ReDim A(0)

A(0) = "('"
For Each Cel In Plage.Cells
    If (Cel.Value <> "" And (InStr(1, A(0), Cel.Value) = 0 Or Doublon)) Then
        A(0) = A(0) & Cel.Value & "', '"
    End If
Next
A(0) = Left(A(0), Len(A(0)) - 3) & ")"

ConcatSQL2 = A(0)
End Function

1 个答案:

答案 0 :(得分:2)

关于@Rory的评论:

  

32767是单元格中的最大字符数

我决定将输出写入文本文件以便以后重复使用!

这是最终的解决方案

Public Function ConcatSQL2(Plage As Range, Optional Doublon As Boolean = True)
Dim A(0 To 0) As String, _
    myFile As String, _
    Cel As Range
'ReDim A(0)

A(0) = "('"
For Each Cel In Plage.Cells
    If (Cel.Value <> "" And (InStr(1, A(0), Cel.Value) = 0 Or Doublon)) Then
        A(0) = A(0) & Cel.Value & "', '"
    End If
Next
A(0) = Left(A(0), Len(A(0)) - 3) & ")"

myFile = "Path\FileName.txt"
Open myFile For Output As #1
Write #1, A(0)
Close #1

ConcatSQL2 = A
End Function