macros中没有任何东西会使Excel 2013崩溃

我正尝试在Excel 2015macros中使用RegEx。 我不知道我是否做错了,但每次运行它,我的Excel崩溃。 这是macros:

Sub MakeExplicit() Dim whitespace As RegExp Set whitespace = New RegExp whitespace.Pattern = "\s+" whitespace.MultiLine = True whitespace.Global = True Dim implicit As RegExp Set implicit = New RegExp implicit.Pattern = "^\d+-\d+$" Dim row As range For Each row In ActiveSheet.UsedRange.Rows Dim first As range Set first = row.Cells(1, 1) Dim str As String str = first.Text str = whitespace.Replace(str, Nothing) If implicit.Test(str) Then 'FIXME here it crashes Dim FromTo As Variant FromTo = Split(str, "-") Dim sFrom, sTo As Integer sFrom = FromTo(1) sTo = FromTo(2) ' doplň chybějící číslice ' např [2345, 78] doplní ' na [2345, 2378] sTo = Left( _ sFrom, _ Len(sFrom) - Len(sTo) _ ) + sTo Dim iFrom, iTo As Integer iFrom = CInt(sFrom) iTo = CInt(sTo) If iFrom > iTo Then _ Err.Raise 42, first.Address, _ "Wrong order of numbers!" Dim i As Integer For i = iFrom To iTo ' some more code Next i End If Next row End Sub 

通过使用debugging器,当代码达到“ If implicit.Test(str) Then ”时,发现它崩溃,意味着RegEx存在问题。 这是项目的参考:

包括Microsoft VBScript正则表达式5.5

显而易见的问题是我如何才能使其工作? VBA本身就是一个非常丑陋的语言,所以我没有偏好如何 ,只是让它工作就足够了。

一些东西…

1)行If implicit.Test(str) Then不应该导致错误。

2)要replace一个或多个空格,不要使用空格,请使用""而不是Nothing

 str = whitespace.Replace(str, "") 

3)由于Split函数返回一个基于0的数组,所以使用…

 sFrom = FromTo(0) sTo = FromTo(1) 

4)连接,使用&符号(&)而不是加号(+)…

  sTo = Left( _ sFrom, _ Len(sFrom) - Len(sTo) _ ) & sTo 

希望这可以帮助!

这是崩溃的路线

 str = whitespace.Replace(str, Nothing) 

Nothing是用于销毁对象… set object = nothing

改用

 str = whitespace.Replace(str, "") 

或者,根据垫子杯子

 str = whitespace.Replace(str, vbNullString) ' uses less memory and is more readable