宏中的“Nothing”崩溃了Excel 2013

时间:2017-08-17 23:44:11

标签: regex excel vba

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

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

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

Microsoft VBScript Regular Expressions 5.5 included

显而易见的问题是如何让它工作? VBA本身就是一种非常难看的语言,因此我对如何没有偏好,只是让它工作就够了。

2 个答案:

答案 0 :(得分:3)

这是崩溃的行

str = whitespace.Replace(str, Nothing)

Nothing用于销毁对象...... set object = nothing

改为使用

str = whitespace.Replace(str, "")

或者,根据Mat's Mug

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

答案 1 :(得分:2)

一些事情......

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

2)要替换一个或多个没有空格的空格,请使用""代替Nothing ...

str = whitespace.Replace(str, "")

3)由于Split函数返回一个从0开始的数组,因此使用...

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

4)要连接,请使用&符号(&)代替加号(+)......

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

希望这有帮助!