【发布时间】:2010-04-12 02:03:33
【问题描述】:
我需要使用 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
【问题讨论】: