簡體   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