繁体   English   中英

使用For循环/ VBA结束If / Next C语句

[英]End If/Next C Statement with For Loop / VBA

我有一个相当复杂的For循环,其中包含一个If语句,而其中包含另一个For循环。 在第二个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM