上下文:我正在编写一个函数,它返回字符串中的单词/数字,用括号括起来。
示例:调用$produktnavn = $xmlObject->item($i)->getElementsByTagName('name')->item(0)->childNodes->item(0)->nodeValue;
应该返回包含两个项ExtractParenthesis("This {should} work. But {doesnt}.")
和should
的集合。
错误:我从以下代码收到的错误是
运行时错误'450':参数数量错误或属性无效 分配
它没有出现在特定的行上,我只是收到一条错误消息“OK”和“帮助”作为选项。
代码:
doesnt
答案 0 :(得分:1)
它完全符合您的需要:
Option Explicit
Public Sub TestMe()
Dim myColl As New Collection
Set myColl = ExtractParenthesis("This {should} work. But {doesnt}.")
Debug.Print myColl(1)
Debug.Print myColl(2)
End Sub
Public Function ExtractParenthesis(strText As String) As Collection
Dim i As Long
Dim RegExp As Object
Dim Matches As Object
Dim Output As New Collection
Set Output = Nothing
Set RegExp = CreateObject("vbscript.regexp")
RegExp.Pattern = "{(.*?)}"
RegExp.Global = True
Set Matches = RegExp.Execute(strText)
For i = 0 To (Matches.Count - 1)
Output.Add Matches(i).submatches(0)
Next i
Set ExtractParenthesis = Output
End Function
我收到"应该"并且"没有"在即时窗口( Ctrl + G )。可能你不知道你正在归还一个系列。它应与Set
关键字一起使用。
要从即时窗口运行它,请尝试这样:
?ExtractParenthesis("This {should} work. But {doesnt}.")(1)
?ExtractParenthesis("This {should} work. But {doesnt}.")(2)
答案 1 :(得分:0)
根据我对你对Vityatas的评论的理解,你的意思是你想把它作为工作表函数运行 - 直接运行
我对您的代码所做的更改将允许您将其用作函数:
在A1:B1
这将有效:{=ExtractParenthesis("This {should} work. But {doesnt}.")}
在A1:A2
中使用它:{=TRANSPOSE(ExtractParenthesis("This {should} work. But {doesnt}."))}
注意:当您使用 Ctrl + Shift + Enter 而非 Enter 输入公式时,Excel会添加花括号。
代码的一个问题是你必须首先选择正确数量的单元格 - 如果它应该返回三个单词,但你只选择了两个单词,那么你只会看到前两个单词。
Public Function ExtractParenthesis(strText As String) As Variant
Dim i As Long
Dim RegExp As Object
Dim Matches As Object
Dim Output As Variant
Set Output = Nothing
Set RegExp = CreateObject("vbscript.regexp")
RegExp.Pattern = "{(.*?)}"
RegExp.Global = True
Set Matches = RegExp.Execute(strText)
ReDim Output(1 To Matches.Count)
For i = 1 To (Matches.Count)
Output(i) = Matches(i - 1).submatches(0)
Next i
ExtractParenthesis = Output
End Function