控制字符检查需要很长时间才能加载

时间:2017-06-16 08:47:47

标签: vba excel-vba for-loop excel

我正在尝试在字符串中搜索特殊字符。

如果字符串中存在特殊字符,则代码将向相邻单元格返回false。

Dim arr(5)

arr(1) = "19"
arr(2) = "26"
arr(3) = "29"
arr(4) = "32"
arr(5) = "50"

'control characters check
For n = 1 To 5
    For x = 1 To 41
        If InStr(1, Range("b" & arr(n)), Chr(x)) = 0 Then
            For y = 123 To 255
                If InStr(Range("b" & arr(n)).Value, Chr(y)) > 0 Then
                    Range("e" & arr(n)).Value = "FALSE"
                    Exit For
                Else
                    Range("e" & arr(n)).Value = "TRUE"
                End If
            Next y
        Else
            Range("e" & arr(n)).Value = "FALSE"
            Exit For
        End If
    Next x
Next n

我的问题是,只需循环几次需要相当长的时间,是否有更快的方法来循环所有数据,从而节省更多时间?

单元格中字符串数据的示例是:TY56D-CAT131BP342AC46-eL-W-00

3 个答案:

答案 0 :(得分:2)

试试这个:

Sub Test()
Dim arr(5) As String
Dim iLen As Integer, strV As String
Dim Found As Boolean: Found = False
Dim Test As Variant

arr(1) = "19"
arr(2) = "26"
arr(3) = "29"
arr(4) = "32"
arr(5) = "50"

For x = 1 To 5
    iLen = Len(Range("B" & arr(x)).Value)
    strV = Range("B" & arr(x)).Value
    For i = 1 To iLen
        Select Case Asc(Mid$(strV, i, 1))
        Case 1 To 41, 123 To 255
            Found = True
            Exit For
        End Select
    Next i
    If Found = False Then
       Range("E" & arr(x)).Value = "TRUE"
    Else
        Found = False
        Range("E" & arr(x)).Value = "FALSE"
    End If
Next x
End Sub

计算时间几乎是即时的。与你的方法有什么不同,我会检查每个字符,然后检查它是否允许。在这种情况下,Select Case可以比每个不允许的char的for循环快得多。

答案 1 :(得分:1)

通过参考

看起来你的速度很慢
Range("b" & arr(n)).Value

循环中可能多达120次(它本身嵌套在其他循环中)

什么应该立即提高宏的速度是在此循环之前将Range值传递给变量,例如:

dim search_string as string
search_string = Range("b" & arr(n)).Value

For y = 123 To 255
     If InStr(search_string, Chr(y)) > 0 Then
     Range("e" & arr(n)).Value = "FALSE"

您还可以节省一些时间将整个搜索范围转换为数组并进行处理,但这需要更多工作,而这是您可以进行的快速更改,这应该可以显着提高性能

答案 2 :(得分:0)

试试这个:

Sub CheckCharacters()
    Dim cl(5) As Integer, n As Integer

    cls = Array(19, 26, 29, 32, 50)

    For n = 0 To 4
        If IsValidString(Range("B" & cls(n))) Then
            Range("B" & cls(n)).Offset(0, 3) = "TRUE"
        Else
            Range("B" & cls(n)).Offset(0, 3) = "FALSE"
        End if
    Next n
End Sub

Function IsValidString(str As String) As Boolean
    Dim objRegEx As Object

    Set objRegEx = CreateObject("vbscript.regexp")

    objRegEx.Pattern = "^[\x2a-\x7a]+"
    objRegEx.Global = True
    objRegEx.IgnoreCase = True

    IsValidString = objRegEx.test(str)
End Function

重要的一点是:

"^[\x2a-\x7a]+"

如果字符串仅包含ASCII值42和122之间的字符(这是您想要的),则此Regex仅为TRUE。