计算VBA中Excel公式的参数数量

时间:2010-04-12 02:03:34

标签: excel vba

我需要使用VBA来确定传递给Excel公式的参数数量。例如,假设一个单元格包含公式= MyFunc($ A $ 1,“xyz”,SUM(1,2,COUNT(C1:C12)),IF(B1> 2,1,0))。然后计数器函数应该返回4. VBA是否包含任何内置函数,或者有人有一个可以计算这个的正则表达式的例子吗?

更新

非常感谢user225626和Charles。我发现的一个问题是当引用包含逗号的字符串参数时;这些逗号导致参数计数增加。我修改了Charles的代码以解释这一点。

Public Function CountFormulaArguments(sStr As String) As Integer
    Dim strChar As String
    Dim nArgs As Integer
    Dim n, nLParen, nCommas As Integer
    Dim blArray, bQuote As Boolean

    nLParen = 0
    nArgs = 0
    For n = 1 To Len(sStr)
        strChar = Mid(sStr, n, 1)
        If strChar = "(" Then
            nLParen = nLParen + 1
            If nLParen = 1 Then nArgs = nArgs + 1
        ElseIf strChar = ")" Then nLParen = nLParen - 1
        ElseIf nLParen = 1 And strChar = "{" Then blArray = True
        ElseIf blArray And strChar = "}" Then blArray = False
        ElseIf Not bQuote And strChar = """" Then bQuote = True
        ElseIf bQuote And strChar = """" Then bQuote = False
        ElseIf nLParen = 1 And Mid(sStr, n, 1) = "," And Not blArray And Not bQuote Then nCommas = nCommas + 1
        End If
    Next
    nArgs = nArgs + nCommas

    CountFormulaArguments = nArgs
End Function

3 个答案:

答案 0 :(得分:1)

扩展Test01以允许在一个语句中使用数组常量和多个函数调用:

=SUM({1,2,3,4,5},{1,2})+SUM({1,2,3,4,5})<br/><br/>

代码:

Sub Test02()
    sStr = Sheets("Sheet1").Range("A2").Formula

    For n = 1 To Len(sStr)
        strChar = Mid(sStr, n, 1)
        If strChar = "(" Then
            nLParen = nLParen + 1
            If nLParen = 1 Then nArgs = nArgs + 1
        End If
        If strChar = ")" Then nLParen = nLParen - 1

        If nLParen = 1 And strChar = "{" Then blArray = True
        If blArray And strChar = "}" Then blArray = False
        If nLParen = 1 And Mid(sStr, n, 1) = "," And Not blArray Then nCommas = nCommas + 1
    Next
    nArgs = nArgs + nCommas

    MsgBox nArgs
End Sub

答案 1 :(得分:0)

Sub Test01()
 sStr = Sheets("Sheet1").Range("A1").Formula

 For n = 1 To Len(sStr)
  If Mid(sStr, n, 1) = "(" Then nLParen = nLParen + 1
  If Mid(sStr, n, 1) = ")" Then nLParen = nLParen - 1

  If nLParen = 1 And Mid(sStr, n, 1) = "," Then nCommas = nCommas + 1
 Next
 nArgs = nCommas + 1

 MsgBox nArgs
End Sub

答案 2 :(得分:0)

UBOUND(数组)

为什么不在参数上使用内置的UBOUND()函数来计算出用户定义函数的数量?

这很简单,但它需要您设置至少一个变量才能拥有无限数量。这是我为我的目的写的:

    Function My_Func(ParamArray others() as variable)

    n = UBound(others) + 1

    'insert code here

    howmanyargumentsinmyfunc = n

    End Function

注意:

  • 'others'表示无限数量的参数被输入我的函数
  • 'n'表示参数总数(由于UBound如何处理数组,您必须添加一个参数)

UBound和ParamArray是用于确定传递给函数的变量数量的关键内置命令。我想,如果你需要将某些值排除在计算之外,你可以使用某种类型的标识来轻松实现。

我希望这有助于某人!