将regexp匹配发送到字符串数组

时间:2012-01-22 21:34:52

标签: regex arrays vba excel-vba excel

我正在尝试使用下面的代码将regexp搜索的结果发送到字符串数组。我怎样才能做到这一点?

当我将名称更改为字符串数组时,Dim name() as String VBA会引发类型不匹配的异常。知道我能做些什么来解决这个问题吗?

非常感谢。

 Do While Not EOF(1)
    Line Input #1, sText
    If sText <> "" Then


       Dim Regex As Object, myMatches As Object

       ' instantiates regexp object
       Set Regex = CreateObject("VBScript.RegExp")
       With Regex
            .MultiLine = False
            .Global = True
            .IgnoreCase = False
            .Pattern = "^Personal\sname\s*[:]\s*"
       End With

       ' get name, seperated from Personal Name
       If Regex.test(sText) Then

            Set myMatches = Regex.Execute(sText)
            Dim temp As String
            temp = Regex.Replace(sText, vbNullString)
            Regex.Pattern = "^[^*]*[*]+"
            Set myMatches = Regex.Execute(temp)
            Dim temp2 As String
            temp2 = myMatches.Item(0)
            name = Trim(Left(temp2, Len(temp2) - 3))

        End If
    End If
Loop

2 个答案:

答案 0 :(得分:3)

您不应将“name”用作变量名,因为它与excel属性冲突。请尝试使用sName或sNames,其中s代表字符串。

使用数组,您需要先为其指定大小,然后才能为每个元素赋值。

Dim sNames(4) As String  '// Or Dim sNames(1 To 4) As String

sName(1) = "John"
...
sName(4) = "Sam"

或者如果您不知道开头的元素(名称)总数:

Dim sNames() As String
Dim iTotalNames As Integer

iTotalNames = '// Some code here to determine how many names you will have

ReDim sNames(iTotalNames) '// You can also use ReDim Preserve if you have existing elements

sName(1) = "John"
...
sName(4) = "Sam"

所以我怀疑你需要这样的东西:

  Dim sNames() As String
  Dim iTotalNames As Integer

  '// Your code ....

  iTotalNames = iTotalNames + 1
  ReDim Preserve sNames(iTotalNames)
  sNames(iTotalNames) = Trim(Left(temp2, Len(temp2) - 3))

  '// Rest of your code ...

同样在VBA中,所有变量的尺寸都应该位于模块的顶部。

答案 1 :(得分:0)

变化

'call this "A"
Dim temp2 As String
temp2 = myMatches.Item(0)

'stick this at the top
 redim temp2(0 to 0)

'replace "A" with this
 new_top = ubound(temp2)+1
 redim preserve temp2 (0 to new_top)
 temp2(new_top) = myMatches.Item(0)