结束如果/下一步C语句与For循环/ VBA
我有一个相当复杂的For
循环里面有一个If
语句和另一个For
循环里面。 并给予一定的标准(即If InStr(1, q.Value, "Total")
)在第二个循环中,我想结束整个If
语句并移到Next C
我明白,这是像洋葱层,可能不是一个简单的出路。
For Each C In copyRng If IsNumeric(C) And C.Value <> "0" And Len(C) <> 0 And C.Value <> "2017" Then Set rowRange = xSheet.Range(C, C.EntireColumn.Cells(1)) 'set range from cell up to the top cell of the comment/ Fix the 2017 thing For Each q In rowRange 'Loop through that range and find the Account number just above it and set it as rowSrc If InStr(1, q.Value, "C-") And Not ISIN(C, uniqueVal) Then Set rowSrc = q If InStr(1, q.Value, "Total") Then End If 'At this point I want to leave the entire If Statement and move on to the next C Next q Set colSrc = C.EntireRow.Offset(0).Cells(1) 'find alert connected with the number numCol = DestSh.Cells.Find(colSrc.Value, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Column 'look for the column in which the same alert is listed numRow = DestSh.Cells.Find(rowSrc.Value, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Row 'look for row in which the same account is listed 'Set destination Set destRng = DestSh.Cells(numRow, numCol) 'Copy to destination Range C.Copy destRng End If Next C
您需要Exit For
,然后在循环之后,将剩余的代码放在另一个If
块中:
For Each C In copyRng If IsNumeric(C) And C.Value <> "0" And Len(C) <> 0 And C.Value <> "2017" Then Set rowRange = xSheet.Range(C, C.EntireColumn.Cells(1)) For Each q In rowRange If InStr(1, q.Value, "C-") And Not ISIN(C, uniqueVal) Then Set rowSrc = q If InStr(1, q.Value, "Total") Then Exit For ' Exit loop prematurely Next q If q is Nothing Then ' Skip if loop was exited prematurely Set colSrc = C.EntireRow.Offset(0).Cells(1) numCol = DestSh.Cells.Find(colSrc.Value, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Column numRow = DestSh.Cells.Find(rowSrc.Value, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Row Set destRng = DestSh.Cells(numRow, numCol) C.Copy destRng End If End If Next C
Then
删除每个下划线Then
重写整个代码。 逻辑改变了。 你几乎没有按照自己的想法去其他地方。
检查这个: VBA – 冒号`:`在VBA条件下的工作条件
一般来说,你的代码不会像你认为的那样工作。 检查以下内容:
Public Sub TestMe() If 1 = 2 Then _ Debug.Print "I am true - 1=2" Debug.Print "I should be also true" If 2 = 3 Then _ Debug.Print "I am true 2=3" End Sub