2012-01-22 43 views
0

我試圖讓下面的代碼將正則表達式搜索的結果發送到字符串數組。我怎樣才能做到這一點?將正則表達式匹配發送到字符串數組

當我將名稱更改爲字符串數組時,即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 

回答

3

您不應該使用「name」作爲變量名稱,因爲它與excel屬性衝突。改爲使用sName或sName,其中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中,變量的所有尺寸都應該位於模塊的頂部。

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)