在VBA中处理UDF中的长string时发生#VALUE错误(excel)

在使用UDF返回长string(> 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错误,但通过debugging,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