我希望在if语句中退出内部之后继续循环外部,逻辑应该是正确的,但我不知道如何编码它。我做了这个,它给了我一个“下一个没有”的错误。想法?
这是我的代码:
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
答案 0 :(得分:2)
您无法启动For
循环,然后在Next
语句中嵌入If
语句。
示例:
For i = 0 To 10
If Range("A1").Value = "" Then
Next
End If
将抛出错误,因为Next在if语句中。正确的方法是:
For i = 0 To 10
If Range("A1").Value = "" Then
End If
Next
看起来你的Next语句太多了。
编辑:
要跳出循环,您可以使用Exit For
例如:
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
会在循环开始时立即增加。
For i = 0 To 10
If i = 5 Then
i = i + 1
End If
Debug.Print i
Next