简体   繁体   中英

Excel VBA Multiple/Nested For Loops

I have a piece of code that loops through 30 columns in one sheet looking for data and then copies this data to a certain destination in another worksheet. The key is that this data will constantly vary. Sometimes I might be copying one column of data, other times all 30 and more commonly something in between.

I have worked out how to loop through my 30 columns of data. However I'm stuck on how to paste each copy next to the last on the destination worksheet. So far it just keeps copying over the top because I haven't worked out how and where to insert the For Loop and make the row/column position variable.

I was wondering if you might be able to look at the code below and advise where this second For Loop should go?

With Sheets("RAW DATA")

    ColumnCount = 30

For i = 2 To ColumnCount

    'For j = 9 To 39

    Dim Rng As Range

    Set Rng = Sheets("RAW DATA").Cells(2, i)

    If Rng.Value <> 0 And Rng.Value <> "" Then

        With Sheets("RAW DATA").Range(Sheets("RAW DATA").Cells(1, i), Sheets("RAW DATA").Cells(16, i))
        .Copy
        End With

        With Sheets("Region")
        .Cells(9, j).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        End With

    Else
    End If

    'Next j

Next i

End With 

Its commented out in the code at the moment but I have been trying to incorporate the Next j part in the right place.

Thanks in advance

As discussed in the commentary section, you can simply start with j = 9 (before your first For loop) and then do j = j + 1 after you paste your values into the Region sheet. There's no need for the second For ... To loop.

(...)
    j = 9
    (...)

    For i = 2 To ColumnCount

        With Sheets("Region")
        .Cells(9, j).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        End With

        j = j + 1
    (...)
    Next i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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