如何在 UDF 中使用 Evaluate 函数来处理长度超过 255 个字符的 Excel 数组公式字符串

问题描述 投票:0回答:1

我曾经使用过类似于LAMDA函数的UDF,其中输入公式是一个字符串。这始终有效,没有任何问题。在 UDF 中,函数字符串使用 Excel

EVALUATE
函数进行处理,并为单个值和数组值返回正确的结果。但现在我有一个本身长度超过 255 个字符的公式。研究结果建议通过 UDF 用公式隐式设置未使用的单元格,计算并获得结果以供进一步处理。现在,这也适用于长公式,但问题是,如果公式返回一个数组(作为数组函数),则该公式也应该是单元格中的数组公式(用大括号括起来)。这是我无法实现的。

这是试用版的简单工作演示代码:

Function one()

Evaluate "two()"
one = "DONE"
End Function

Function two()

a = "=Len(""this is a very very very very very long long long string which must be resolved in a value which is over 255 vcharacter""&" & """ length but i need the total length of the value. My problerm is that I have to do it with a user defined function and cannot separate the length of it. It will works for me? This was my question."")"
Range("a1").Formula = a
Debug.Print a

End Function

在工作表代码模块上

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$E$6" Then
Calculate
End If
End Sub

在表中:

A B C D E
14 14
54
34
2
134
87 =一()

单元格 E6 是 UDF 调用者,单元格 A1 用于结果。在这种情况下返回 315。

A B C D E
315 14 14
54
34
2
134
87 完成

问题是我是否换线

Range("a1").Formula = a

Range("a1").FormulaArray = a

代码运行没有错误,但单元格 A1 仍为空。

如何将单元格公式设置为数组公式。这是在使用 CSE 的 Excel 中。(Ctrl+Shift+Enter)

excel vba user-defined-functions array-formulas evaluate
1个回答
0
投票

不确定我完全遵循这个问题,但这是“公式中的字符串太长”的一种解决方法。 将字符串分成块并在公式中将它们连接起来。

Sub Tester()
    
    Dim longString As String
    
    longString = "this is a very very very very very long long long string " & _
       " which must be resolved in a value which is over 255 vcharacter" & _
       " length but i need the total length of the value. My problerm is that" & _
       " I have to do it with a user defined function and cannot separate " & _
       "the length of it. It will works for me? This was my question."
    
    'Range("a1").Formula = "=Len(""" & longString & """)"                  'fails
    Range("a2").Formula = "=Len(""" & TextSplit(longString) & """)"        'works
    
End Sub

Function TextSplit(txt) As String
    Const MAX_CHUNK As Long = 200
    Dim s As String, i As Long, sep As String
    If Len(txt) > MAX_CHUNK Then
        i = 1
        Do While i < Len(txt)
            s = s & sep & Mid(txt, i, MAX_CHUNK)
            i = i + MAX_CHUNK
            sep = """ & """
        Loop
    End If
    TextSplit = s
End Function
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.