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

牧云@^-^@ 提交于 2020-01-17 11:34:42

问题


I've encountered #VALUE error when using an UDF returning an array with long strings (>256 symbols).

Sample Code:

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

When calling longString() as an array formula in a cell, the cell got #Value error, but through debugging, longString() returns without error.

how can i resolve this issue?


回答1:


I believe you have run into one of the obscure limitations in the interactions between VBA and Excel.

One workaround would be to change the formula to return only a single element, and have the particular element as an argument in the UDF.

For example:


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

You could then call the function in any of the following ways:

=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


来源:https://stackoverflow.com/questions/27700456/value-error-when-dealing-with-long-string-in-udf-in-vbaexcel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!