繁体   English   中英

在VBA中处理UDF中的长字符串时出现#VALUE错误(excel)

[英]#VALUE error when dealing with long string in UDF in VBA(excel)

使用UDF返回带有长字符串(> 256个符号)的数组时遇到了#VALUE错误。

样例代码:

Function longString() As Variant
        Dim res(1 To 1, 1 To 2)
        res(1, 1) = "hellohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\nhellohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\nhellohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\nhellohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhellohh\n"
        res(1, 2) = "world"
        longString = res
End Function

在单元格中将longString()作为数组公式调用时,该单元格出现#Value错误,但通过调试,longString()返回时没有错误。

我该如何解决这个问题?

我相信您在VBA和Excel之间的交互中遇到了一个晦涩的局限性之一。

一种解决方法是将公式更改为仅返回单个元素,并将特定元素作为UDF中的参数。

例如:


Option Explicit
Function longString(Optional R As Long = 1, Optional C As Long = 1)
        Dim res(1 To 1, 1 To 2)
        res(1, 1) = "hellohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\nhellohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\nhellohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\nhellohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhellohh\n"
        res(1, 2) = "world"
        longString = res(R, C)
End Function

然后,您可以通过以下任意一种方式调用该函数:

=longString()      <-- returns the first element
=longString(1,1)   <-- returns the first element
=longString(1,2)   <-- returns the second element
=longString(ROWS($1:1), COLUMNS($A:A))  <--could be dragged down and right to return an array of the elements

暂无
暂无

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

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