首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >退出并继续循环上层

退出并继续循环上层
EN

Stack Overflow用户
提问于 2013-07-31 18:39:38
回答 1查看 83关注 0票数 0

在if语句中退出内部for之后,我想继续循环外部,逻辑应该是正确的,但我不知道如何对其进行编码。我这样做了,它给了我一个"next无for“错误。想法?

这是我的代码:

代码语言:javascript
复制
For InrCounter = 2 To InrNum
    For ExrCounter = 2 To Exrnum

            'add missing column data from input sheet to existing sheet
            lastCofthisR = sheet1Table.Cells(ExrCounter, Columns.Count).End(xlToLeft).Column

            'searching for address
            If sheet1Table.Cells(InrCounter, 1) = sheet2Table.Cells(ExrCounter, 1) And sheet1Table.Cells(InrCounter, 2) = sheet2Table.Cells(ExrCounter, 2) And sheet1Table.Cells(InrCounter, 3) = sheet2Table.Cells(ExrCounter, 3) Then
                If lastCofthisR < IncNum Then
                    For LastCofRowCounter = lastCofthisR + 1 To IncNum
                        Sheets("Sheet1").Cells(ExrCounter, LastCofRowCounter) = Sheets("Sheet2").Cells(InrCounter, LastCofRowCounter)
                    Next LastCofRowCounter

                    'found match loop next input row
                    Exit For
                    Next InrCounter
                Else
                    'do nothing
                End If
            Else
                Next ExrCounter
                'do nothing
            End If


            'did not find the input row, find the last row of existing and add it
            lrowEx = Sheets("Sheet1").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
            For counterCofLastR = 1 To IncNum
                Sheets("Sheet1").Cells(lrowEx + 1, counterCofLastR) = Sheets("Sheet2").UsedRange.Columns(1).Cells(InrCounter, counterCofLastR)
            Next counterCofLastR
     Next InrCounter
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-31 18:59:29

不能启动For循环,然后将Next语句嵌入到If语句中。

示例:

代码语言:javascript
复制
For i = 0 To 10
    If Range("A1").Value = "" Then
    Next
End If

将引发一个错误,因为Next在if语句中。这样做的适当方法是:

代码语言:javascript
复制
For i = 0 To 10
    If Range("A1").Value = "" Then
    End If
Next

接下来的语句看起来也太多了。

编辑:

要跳出循环,可以使用Exit For

例如:

代码语言:javascript
复制
For i = 0 To 10
    For x = 0 To 10
        Exit For
        Debug.Print x
    Next
    Debug.Print i
Next

只有i才能打印0到10,因为内环会按Exit For

如果要跳过循环迭代,可以手动增加循环计数器。例如,下面的代码将跳过5,因为i在循环开始时立即增加。

代码语言:javascript
复制
For i = 0 To 10
    If i = 5 Then
        i = i + 1
    End If
    Debug.Print i
Next
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17978296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档