简体   繁体   English

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

[英]Error #VALUE with long string in UDF in VBA for output in Excel

I use the below UDF to concatenate references to include the result in 我使用下面的UDF连接引用以将结果包含在
an SQL query like ref in ('ref1', 'ref2', ...) . ref in ('ref1', 'ref2', ...)的SQL查询。

The UDF works just fine normally , but when I need to put a huge list of references, UDF 通常可以正常工作 ,但是当我需要放置大量引用时,
I get #VALUE in Excel . 我在Excel中得到#VALUE

I already take a look at this answer , but I can't manage to make my UDF work... 我已经看过这个答案 ,但是我无法使UDF正常工作...

I've tried to changed the type of the function from String to Variant (explicitly), 我试图将函数的类型从String更改为Variant (显式),
but it didn't change a thing... 但这并没有改变任何事情...

I also tried ConcatSQL2 = A(0) and ConcatSQL2 = A for the output, 我还尝试了ConcatSQL2 = A(0)ConcatSQL2 = A作为输出,
Dim A(0 To 0) As String for the declaration, ... and again it is not working... Dim A(0 To 0) As String声明的Dim A(0 To 0) As String ,...又一次不起作用...
I'm running out of ideas... 我的想法不多了...

For info, the result string is expected to be about 220k long ... 对于信息, 结果字符串预计约为220k长 ...
To help you generate a lot of text, you can use the Lorem Ipsum generator here! 为了帮助您生成大量文本,您可以在此处使用Lorem Ipsum生成器!

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

Regarding @Rory's comments : 关于@Rory的评论:

32767 is the maximum number of characters in a cell 32767是一个单元格中的最大字符数

I decided to write the output in a text file to be reused afterwards! 我决定将输出写入一个文本文件中 ,然后再使用!

Here is the final solution 这是最终的解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM