我正在尝试在VBA中创建一个UDF,它通过一些函数语法并将其视为Text。
该功能如下:
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
感谢您的帮助
答案 0 :(得分:3)
Split
应该可以工作,但要正确处理嵌套函数的情况,初步的hack是首先用安全分隔符(例如[[,]]
)替换顶层的逗号,然后拆分它定界符:
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
我认为没有充分的理由让这个功能变得不稳定。