我尝试使用Regularexpressions匹配文本中的模式,但是我得到此运行时错误。你能帮我解决这个问题吗?
运行时错误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
更新
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
答案 0 :(得分:2)
您尚未创建正则表达式对象(仅声明对象占位符):
(这是VBScript而不是VBA; VBScript的正则表达式包含您在发布的代码中使用的方法)
Dim regexp as New RegExp
如果您真的想在VBA中使用它(但您必须更改代码中调用的方法):
Dim regexp As Object
Set re = CreateObject("vbscript.regexp")
... Use regexp
Set regexp = Nothing
参考文献:
答案 1 :(得分:1)
首先要检查的是您是否在VBA模块的顶部定义了Option Explicit
。我怀疑你没有,因为你的代码中有几个未声明的变量。使用Option Explicit
可以防止由于未声明的变量,拼写错误等引起的头痛。
接下来,您的代码进入无限循环,因为您正在循环While Not ts.AtEndOfStream
,但您实际上从未读取来自TextStream的任何内容,因此您永远不会结束
以下版本的代码似乎对我有用:
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