解析函数的参数

Parsing the Parameters of a Function

我正在尝试在 VBA 中创建一个 UDF,它通过一些函数语法并将其视为文本。

该函数将如下所示:

FunctionA( Param1 , Param2 , Param3 , Param 4 )

我正在尝试开发一个 UDF,它将根据我输入到 UDF 函数中的位置提取 Param 的值。

GetN( FunctionA , 3 ) = "Param3"

GetN FunctionA , 1 ) = "Param1"  

到目前为止,这是我的功能,但它已关闭....

它的行为就像:

GetN( FunctionA , 0 ) = Param2 

这是我的函数:

Function GetN(sInputString As String, n As Integer) As String
     Dim sFindWhat As String
     Dim j, FindA, FindB As Integer
     Application.Volatile
     sFindWhat = ","

     FindA = 0
     For j = 0 To n
         FindA = InStr(FindA + 1, sInputString, sFindWhat)
         FindB = InStr(FindA + 1, sInputString, sFindWhat)
         If FindB = 0 Then FindB = InStr(FindA + 1, sInputString, ")")
         If FindA = 0 Then Exit For
     Next
     GetN = Trim(Mid(sInputString, FindA + 1, FindB - FindA - 1))

 End Function

感谢您的帮助

Split 应该可以工作,但要正确处理嵌套函数的情况,初步的技巧是首先用安全分隔符(例如 [[,]])替换顶层的逗号,然后拆分在该分隔符上:

Function GetParameterN(func As String, n As Long) As String
    Dim args As Variant
    Dim safeArgs As String
    Dim c As String
    Dim i As Long, pdepth As Long

    func = Trim(func)
    i = InStr(func, "(")
    args = Mid(func, i + 1)
    args = Mid(args, 1, Len(args) - 1)

    For i = 1 To Len(args)
        c = Mid(args, i, 1)
        If c = "(" Then
            pdepth = pdepth + 1
        ElseIf c = ")" Then
            pdepth = pdepth - 1
        ElseIf c = "," And pdepth = 0 Then
            c = "[[,]]"
        End If
        safeArgs = safeArgs & c
    Next i
    args = Split(safeArgs, "[[,]]")
    GetParameterN = Trim(args(n - 1))
End Function

例如,

Sub test()
    Dim i As Long
    For i = 1 To 3
        Debug.Print GetParameterN("f(x,g(x,y,z),z)", i)
    Next i
End Sub

生产:

x
g(x,y,z)
z

我认为没有充分的理由让这个函数可变。