如果有多个或语句创建无限循环

时间:2017-03-16 13:53:21

标签: vba excel-vba excel

我有一个循环,沿着列向下,并确定该单元格是否等于列出的安全类型之一。如果没有,它将剪切并粘贴数据偏移1列到左边。有时数据偏移1-3列,这就是为什么我添加i = i - 1来检查同一行,直到它满足if。此代码导致2个问题:

1。)If语句是否有一个更简单的代码行,带有多个或者?

2。)这段代码分段工作,但当它在整张纸上运行时(约29K行),它会进入无限循环。任何想法为什么会这样?

LastCashrow = Sheets("Cash Data").Range("A" & Sheets("Cash Data").Rows.Count).End(xlUp).Row

For i = 8 To LastCashrow

SecType = Left(Cells(i, 5), 2)

  If SecType = "aw" Or SecType = "ca" Or SecType = "cb" Or SecType = "cd" Or SecType = "cl" Or SecType = "cp" Or SecType = "cs" Or SecType = "cv" Or SecType = "ep" _
                Or SecType = "ex" Or SecType = "fi" Or SecType = "fm" Or SecType = "gb" Or SecType = "gm" Or SecType = "hf" Or SecType = "lp" Or SecType = "mb" _
                Or SecType = "mf" Or SecType = "oa" Or SecType = "pf" Or SecType = "pr" Or SecType = "ps" Or SecType = "pt" Or SecType = "re" Or SecType = "rl" _
                Or SecType = "tb" Or SecType = "tp" Or SecType = "ut" Or SecType = "wt" Or SecType = "zb" Or SecType = "zt" Then

  ElseIf IsEmpty(SecType) = "True" Then
        Exit For

  Else
        Set Shift = Range(Cells(i, 5), Cells(i, 17))
        Shift.Cut
        Cells(i, 4).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        i = i - 1

  End If

Next i

2 个答案:

答案 0 :(得分:1)

1。)If语句是否有更简单的代码行,包含多个或者<?em>

是。我开始以这种方式改进您的代码:

' Declare all of your variables explicitly
Dim LastCashRow As Long
Dim i As Long
Dim SecType As String
Dim cell As Range

Dim validSecTypes() As String
validSecTypes = Split("aw,ca,cb,cd", ",") ' write all of your values here...
' returns an array of strings: ["aw", "ca", "cb", "cd"]

LastCashRow = 12

For i = 8 To LastCashRow
    Set cell = Cells(i, 5)
    If IsEmpty(cell) Then Exit For ' This is really the first thing to check for.

    SecType = Left(cell.Value, 2)

    If ArrayContains(validSecTypes, SecType) Then 
        MsgBox SecType & " is IN!"
    Else
        MsgBox "This is OUT: " & SecType
        'your lines of code go here
    End If

Next i

这使用辅助函数:

Function ArrayContainsValue(arr As Variant, val As Variant) As Boolean
    ArrayContainsValue = (UBound(Filter(arr, val)) > -1)
End Function

2。)此代码分段工作,但当它在整个工作表(~29K行)上运行时,它进入无限循环。有什么想法会发生这种情况吗?

<击> 不,我们必须看你的表。

<击>

但你真的确定它是无止境的吗?因为使用当前编写的代码处理许多行可能需要一些时间。

正如我猜测的那样,你的代码需要很长时间才能运行。

罪魁祸首可能是这段代码:

    Shift.Cut
    Cells(i, 4).Select
    ActiveSheet.Paste

答案 1 :(得分:0)

您可以这样做以简化倍数或条件:

If InStr(1, "/aw/ca/cb/cd/cl/cp/cs/cv/ep/ex/fi/fm/gb/gm/hf/lp/mb/mf/oa" + _
            "/pf/pr/ps/pt/re/rl/tb/tp/ut/wt/zb/zt", SecType) > 1 Then