像条件一样循环

时间:2016-10-26 13:45:54

标签: excel-vba loops if-statement vba excel

我有以下问题。

在下面的代码中,我试图让我的sub在if then语句之后运行一个循环,然后让代码返回到第一个循环并从下一个i开始。在我的下面的代码中,一切正常,但是当满足第一个IF语句中的条件时,它会启动第二个循环,但随后会在不运行它的情况下再次退出。

所以我的问题是,如何在IF语句中的then语句之后进行循环?

var allData = [
    {
      id:'10',
      name:'jhon'
    },
    {
      id:'11',
      name:'lewis'
    },
    {
      id:'12',
      name:'taylor'
    },
    {
      id:'13',
      name:'adam'
    },
    {
      id:'14',
      name:'bolive'
    }
];

var addedIds = ['10', '12', '14'];

var allData = allData.filter(function (item) {   
    if (addedIds.indexOf(item.id) !== -1) return item;
});

console.log(allData);

2 个答案:

答案 0 :(得分:2)

始终使用Option Explicit。这会让你黯然失色并设置LastRow_2,然后尝试使用Last_row_2 ......

答案 1 :(得分:0)

代码审查

在仔细审核您的代码后,我认为您的问题不适用于您的问题。你有很多错误,我已在下面为你纠正过:

Option Explicit
Sub Sort3()
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("EQ_CLEAN")
    Dim LastRow As Long, LastRow_2 As Long
    Dim lenght As String
    Dim L_text As String, R_text As String, M_text As String
    Dim n As Long, x As Long, i As Long

    LastRow = ws.Cells(ws.Rows.Count, "G").End(xlUp).Row

    LastRow_2 = ws.Cells(ws.Rows.Count, "J").End(xlUp).Row

    For i = 2 To LastRow

        lenght = ws.Range("G" & i).Value

        If Len(lenght) = 25 Then

            L_text = Left(ws.Range("A" & i).Value, 12)
            R_text = Right(ws.Range("A" & i).Value, 12)

            For x = 2 To LastRow_2

                'On Error Resume Next 'You should never use this unless you know exactly which error
                'is popping up and why it can't be avoided. Usually this is for 1004 errors that occur
                'outside of excel... It's better to use proper error handling instead of skipping all errors.
                'You also never tell excel to recognize errors via On Error GoTo 0. I advise you stay away
                'from handling errors with these two statements.

                'don't make it a habit to assign rogue variables values
                n = ws.Range("D1:D6000").Cells.SpecialCells(xlCellTypeConstants).Count

                If L_text <> ws.Range("J" & x).Value Then
                    ws.Range(ws.Cells(x, 1), ws.Cells(x, 2)).Copy
                    ws.Range("D" & (n + 1)).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
                        SkipBlanks:=False, Transpose:=False
                    Application.CutCopyMode = xlCopy 'this is the proper format to remove the marching ants
                End If
            Next x
        End If
    Next i
End Sub

我试图将评论放在更改的位置。

我在一张白纸上运行你的代码并没有抛出任何错误。看看它是否能达到你想要的效果。

参考文献

<强> Error Handling

<强> Avoiding Use of .Select

<强> What Microsoft says about Option Explicit

<强> Why I changed your Row based variables to Long

相关问题