将Excel公式字符串解析为VBA中的前置字符串、函数、参数和后置函数字符串
对于给定的Excel函数,例如VLOOKUP,我需要将单元格的公式字符串解析为: preFunctionStr=VLOOKUP函数前面的字符串 ExcelFn=VLOOKUP Arguments=VLOOKUP函数中所有参数的集合,这些参数本身可能包含函数 postFunctionStr=公式字符串中最后一个后面的字符串 我希望这样做的主要原因是能够转换Excel公式而不改变它们的答案。例如,将SUMIF转换为SUMIFS,并将VLOOKUP转换为索引和匹配的组合 在我的示例中,我所在的单元格包含公式=A4+VLOOKUP2,$E$4:$F$8,MATCHValue1,$E$4:$F$4,0,0+2000,我需要将其解析为上述组件将Excel公式字符串解析为VBA中的前置字符串、函数、参数和后置函数字符串,excel,vba,parsing,Excel,Vba,Parsing,对于给定的Excel函数,例如VLOOKUP,我需要将单元格的公式字符串解析为: preFunctionStr=VLOOKUP函数前面的字符串 ExcelFn=VLOOKUP Arguments=VLOOKUP函数中所有参数的集合,这些参数本身可能包含函数 postFunctionStr=公式字符串中最后一个后面的字符串 我希望这样做的主要原因是能够转换Excel公式而不改变它们的答案。例如,将SUMIF转换为SUMIFS,并将VLOOKUP转换为索引和匹配的组合 在我的示例中,我所在的单元格包
虽然我可以找到大量有关解析Excel公式的资料,但我找不到将其分解为这些组件的资料。在我的解决方案中,我创建了一个类模块,该模块的属性需要将公式字符串分解为ExcelFormulaParser: 为了提供如何调用和使用类模块的示例,我在同一VBA项目中创建了以下模块:
Sub TestFormulaParser()
Dim ParsedForm As ExcelFormulaParser
Set ParsedForm = New ExcelFormulaParser
Dim StrToParse As String
StrToParse = ActiveCell.Formula
' formula contains:
'' =A4+VLOOKUP(2,$E$4:$F$8,MATCH("Value(1)",$E$4:$F$4,0),0) + 2000
Call ParsedForm.SetMeUp(StrToParse, "VLOOKUP")
preFunctionStr = ParsedForm.preFunctionStr
' returns the prefunction string i.e. =A4+
ExcelFn = ParsedForm.ExcelFn
' returns the excel function we parsed i.e. VLOOKUP
Arg1 = ParsedForm.Arguments(1)
' returns the first argument of the VLOOKUP function i.e. 2
Arg2 = ParsedForm.Arguments(2)
' returns the second argument of the VLOOKUP function i.e. $E$4:$F$8
Arg3 = ParsedForm.Arguments(3)
' returns the third argument of the VLOOKUP function i.e. MATCH("Value(1)",$E$4:$F$4,0)
Arg4 = ParsedForm.Arguments(4)
' returns the fourth argument of the VLOOKUP function i.e. 0
postFunctionStr = ParsedForm.postFunctionStr
' returns the post function string i.e. + 2000
End Sub
因此,您找到了解决问题的方法,还是存在一些遗留问题?如果是,哪些解决方案?@h2so4我对我的解决方案很满意,并希望与社区分享,因为我无法在网上找到其他解决方案。如果其他人能在这方面有所改进,那也会很好。例如,如果您不需要使用类模块,它可能会更干净?
Sub TestFormulaParser()
Dim ParsedForm As ExcelFormulaParser
Set ParsedForm = New ExcelFormulaParser
Dim StrToParse As String
StrToParse = ActiveCell.Formula
' formula contains:
'' =A4+VLOOKUP(2,$E$4:$F$8,MATCH("Value(1)",$E$4:$F$4,0),0) + 2000
Call ParsedForm.SetMeUp(StrToParse, "VLOOKUP")
preFunctionStr = ParsedForm.preFunctionStr
' returns the prefunction string i.e. =A4+
ExcelFn = ParsedForm.ExcelFn
' returns the excel function we parsed i.e. VLOOKUP
Arg1 = ParsedForm.Arguments(1)
' returns the first argument of the VLOOKUP function i.e. 2
Arg2 = ParsedForm.Arguments(2)
' returns the second argument of the VLOOKUP function i.e. $E$4:$F$8
Arg3 = ParsedForm.Arguments(3)
' returns the third argument of the VLOOKUP function i.e. MATCH("Value(1)",$E$4:$F$4,0)
Arg4 = ParsedForm.Arguments(4)
' returns the fourth argument of the VLOOKUP function i.e. 0
postFunctionStr = ParsedForm.postFunctionStr
' returns the post function string i.e. + 2000
End Sub