【问题标题】:#VALUE error when dealing with long string in UDF in VBA(excel)在 VBA 中处理 UDF 中的长字符串时出现 #VALUE 错误(excel)
【发布时间】:2014-12-30 19:21:31
【问题描述】:

我在使用返回包含长字符串(>256 个符号)的数组的 UDF 时遇到 #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()返回没有错误。

我该如何解决这个问题?

【问题讨论】:

  • 您的代码不会在我的机器上引发任何错误 (Excel 2010)。你是哪个版本的?
  • @silentsurfer 您是否在工作表单元格中输入了 UDF 作为公式?它在 Excel 2007 的该单元格中返回 #VALUE! 错误。

标签: excel vba excel-udf


【解决方案1】:

我相信您在 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

【讨论】:

  • 谢谢。解决方法有效。很高兴知道这是仅影响数组的模糊限制之一。
  • 刚从 MSDN 论坛得到答案,字符串数组需要明确清除。 IE。 Dim res(1 To 1, 1 To 2) as String。然后它将接受长字符串。
  • @TerenceHang 是的。出于某种原因,当我注意到您已将函数的返回类型显式声明为 Variant,并将 res 隐式声明为 Variant 时,我为您提供了一种可以保留这些数据类型的解决方法。将 res 声明为字符串的一个可能不受欢迎的副作用是数字数据将作为字符串返回。因此被某些函数忽略。
猜你喜欢
  • 2016-03-17
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
相关资源
最近更新 更多