0

如何从 Visual Basic 中的字符串中提取 excel 函数(仅它们的名称)?

例如我有: Sin(B6)*Sum(A2:A4) 所以我想找到一种方法来从中获得“Sin”和“Sum”。

注意:我已经有一个提取单元格地址的代码,它可能会给你一个提示来帮助我。

谢谢你。

Dim result As Object
Dim testExpression As String
Dim objRegEx As Object
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
objRegEx.Pattern = """.*"""  ' remove expressions
testExpression = Mystring
testExpression = objRegEx.Replace(testExpression, "")
objRegEx.Pattern = "(([A-Z])+(\d)+)"  'grab the address
    Dim i As Long
Dim k As Long
If objRegEx.test(testExpression) Then
    Set result = objRegEx.Execute(testExpression)
    If result.Count > 0 Then

        For Each Match In result

k = Len(Match.value)
i = 1
Do Until (i > k) Or (IsNumeric(Mid$(Match.value, i, 1)))
    i = i + 1
Loop

Debug.Print Match.value

        Next Match
       End if
4

1 回答 1

3

假设一个函数(调用)以一个体面的字母 ([AZ]) 开头,后跟至少一个标识符字符(\w+:字母、数字、_),然后是可选的 withspace 和参数列表的左括号:

  Dim aTests : aTests = Array( _
      "Sin(B6)*Sum(A2:A4)" _
    , "sum_02(B6) * Do_what_I_Mean( A2:A4 )" _
    , "Sum(Sum(Sum(A2:A4)))" _
    , "NoArgsFunc()" _
  )
  Dim reFunc : Set reFunc = New RegExp
  reFunc.Global     = True
  reFunc.IgnoreCase = True
  reFunc.Pattern    = "([A-Z]\w+)\s*\("
  Dim sTest
  For Each sTest In aTests
      WScript.Echo "----", qq(sTest)
      Dim oMT
      For Each oMT In reFunc.Execute(sTest)
          WScript.Echo qq(oMT.SubMatches(0))
      Next
  Next

输出:

---- "Sin(B6)*Sum(A2:A4)"
"Sin"
"Sum"
---- "sum_02(B6) * Do_what_I_Mean( A2:A4 )"
"sum_02"
"Do_what_I_Mean"
---- "Sum(Sum(Sum(A2:A4)))"
"Sum"
"Sum"
"Sum"
---- "NoArgsFunc()"
"NoArgsFunc"

附言

由于 . (除 EOL 外的所有内容)和贪婪。测试它"YourRegExp("""") & Sucks("""")"并考虑一个类似的模式"""[^""]*"""并用"""""".

于 2013-05-11T14:28:55.673 回答