1

我尝试使用正则表达式匹配文本中的模式,但出现此运行时错误。你能帮我解决这个问题吗?

运行时错误 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
4

2 回答 2

2

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

(这是 VBScript 而不是 VBA;VBScript 的正则表达式具有您在发布的代码中使用的方法)

Dim regexp as New RegExp

如果你真的想要在 VBA 中这样做(但你必须更改代码中调用的方法):

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

... Use regexp


Set regexp = Nothing

参考:

微软用正则表达式强化 VBScript

VBA中的正则表达式匹配

于 2013-06-03T08:15:29.063 回答
1

首先要检查的是您是否已Option Explicit在 VBA 模块的顶部定义。我怀疑你没有,因为你的代码中有几个未声明的变量。使用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
于 2013-06-03T09:42:59.990 回答