2013-06-03 59 views
1

我尝试使用Regularexpressions匹配文本中的模式,但是我得到此运行时错误。你能帮我解决这个问题吗?解决我的代码中的运行时错误91

运行时错误91: 对象变量或与块变量未设置

代码:

Dim fso As New FileSystemObject 
Dim ts As TextStream 
Dim Name As String 
Dim regexp As Object 
Dim colregmatch As MatchCollection 

Name = "D:/test_DC.txt" 
Set ts = fso.OpenTextFile(Name, ForReading) 
Do While Not ts.AtEndOfStream 
regexp.Pattern = "KENNFELD\s+([ 0-9]*)" //Error 
    Set colregmatch = regexp.Execute(searchstr) 
    If colregmatch.Count <> 0 Then 
     For Each Match In colregmatch 
      MsgBox Match 
     Next Match 
End If 
Loop 

UPDATE:

Dim fso As New FileSystemObject 
Dim ts As TextStream 
Dim Name As String 
Dim regx As New regexp 
Dim colregmatch As MatchCollection 

Name = "D:/test_DC.txt" 
'Set regexp = CreateObject("vbscript.regexp") 
Set ts = fso.OpenTextFile(Name, ForReading) 
Do While Not ts.AtEndOfStream 
    regx.Pattern = "KENNFELD\s+([ 0-9]*)" 
    Set colregmatch = regx.Execute(searchstr) 
    If colregmatch.Count <> 0 Then 
     For Each Match In colregmatch 
      MsgBox Match 
     Next Match 
End If 
Loop 

回答

2

您尚未创建一个正则表达式对象(只声明一个对象占位符):

(这是VBScript不是VBA; VBScript的正则表达式有您使用

Dim regexp as New RegExp 

如果你真的想这样在VBA方法在你的发布代码)(但你必须要改变所谓的在你的代码的方法):

Dim regexp As Object 
Set re = CreateObject("vbscript.regexp") 

... Use regexp 


Set regexp = Nothing 

参考文献:

Microsoft Beefs Up VBScript with Regular Expressions

Regex match in VBA

+0

如果我改变我的代码,我看不出有什么错误,但程序就进入无响应的情况,我必须重新启动它。我已经更新了上面的代码 – TangoStar

1

首先要检查的是您是否在您的VBA模块的顶部定义了Option Explicit。我怀疑你没有,因为你的代码中有几个未声明的变量。使用Option Explicit将阻止未声明的变量,错别字等引起头痛的地段..

接下来,你的代码,因为你是在While Not ts.AtEndOfStream循环进入一个死循环,但你从来没有真正读取来自文本流任何东西,所以你永远不会走到尽头。

代码的下面的版本似乎为我工作:

Sub regexpTest() 
Dim fso As New FileSystemObject 
Dim ts As TextStream, searchstr As String 
Dim Name As String 
Dim regx As New regexp 
Dim colregmatch As MatchCollection, matchItem As match 

Name = "D:\test_DC.txt" 
'' Set regexp = CreateObject("vbscript.regexp") 
Set ts = fso.OpenTextFile(Name, ForReading) 
Do While Not ts.AtEndOfStream 
    searchstr = ts.ReadLine 
    regx.Pattern = "KENNFELD\s+([ 0-9]*)" 
    Set colregmatch = regx.Execute(searchstr) 
    If colregmatch.Count <> 0 Then 
     For Each matchItem In colregmatch 
      MsgBox matchItem 
     Next matchItem 
     Set matchItem = Nothing 
    End If 
    Set colregmatch = Nothing 
Loop 
'' clean up 
ts.Close 
Set ts = Nothing 
Set regx = Nothing 
Set fso = Nothing 
End Sub