Excel 如何退出嵌套循环?

Excel 如何退出嵌套循环?,excel,vba,Excel,Vba,我需要帮助控制嵌套If…then语句中循环的重复。如何确保I=5和I=6的操作只发生一次 For i = 5 To 26 Set sht = wkbk.Sheets(i) sht.Cells(3, 1).Value = "'" & StrConv(inputbx, vbProperCase) & " 2017" If i = 5 Or 6 Then Cells(7, 6).End(xlToRight).EntireColumn.Select

我需要帮助控制嵌套If…then语句中循环的重复。如何确保I=5和I=6的操作只发生一次

For i = 5 To 26
    Set sht = wkbk.Sheets(i)
    sht.Cells(3, 1).Value = "'" & StrConv(inputbx, vbProperCase) & " 2017"
    If i = 5 Or 6 Then
        Cells(7, 6).End(xlToRight).EntireColumn.Select
        Selection.AutoFill Destination:=Range(Selection, Selection.Offset(0, 1))
    End If
Next i

更改if并确保引用的图纸正确:

Dim clm As Long
For i = 5 To 26
    With wkbk.Sheets(i)
        .Cells(3, 1).Value = "'" & StrConv(inputbx, vbProperCase) & " 2017"
        If i = 5 Or i = 6 Then
            clm = .Cells(7, 6).End(xlToRight).Column
            .Columns(clm).AutoFill Destination:=.Range(.Columns(clm), .Columns(clm).Offset(0, 1))
        End If
    End With
Next i

如果希望嵌套if只在5和6中发生一次,请添加一个新变量:

Dim to_work = true
For i = 5 To 26
    Set sht = wkbk.Sheets(i)
    sht.Cells(3, 1).Value = "'" & StrConv(inputbx, vbProperCase) & " 2017"
    If (i = 5 Or i = 6) and to_work Then
        sht.Cells(7, 6).End(xlToRight).EntireColumn.Select
        Selection.AutoFill Destination:=Range(Selection, Selection.Offset(0, 1))
        to_work = false
    End If
Next i

如果他们真的只希望它发生一次,他们可以将
If
更改为
If i=5,然后
。计算依赖项可能要求它在循环中执行(很难从一段代码中分辨出来),但我试图理解的要点是,不需要新的变量。我最终为指令创建了一个单独的循环。我决定分开,因为这两个动作根本没有关系。你的“i=5和i=6只有一次”模棱两可。我猜你的意思是“仅当I=5和I=6时”,但也可以解释为“仅当I=5或I=6时一次(但不适用于两者)”。请确认您的意思。如果您处于5到26的增量循环中,并且您只想在i=5或6时执行某项操作,但仅执行一次,那么在i=6时将永远不会执行该操作,因为5总是首先触发它。我认为您希望在这两种情况下都触发它,这意味着您只需要在6之前使用
I=
。不要使用select,查看Scotts帖子了解如何避免它。