Why doesn't this for loop process the full data set?

前端 未结 3 1225
轮回少年
轮回少年 2021-01-19 06:04

Background

I have a spreadsheet of ticket allocations for an event. On each row of the spreadsheet is a name and the number of tickets allocated.

3条回答
  •  粉色の甜心
    2021-01-19 06:11

    To keep using the For...Next loop, you could do:

    For r = LastRow To 1 Step -1
        surname = Cells(r, surnameCol).Value
        tickets = Cells(r, ticketCol).Value
    
        If (Not (Len(surname) = 0)) Then
            Cells(r, targetCol).Value = surname
    
            For x = 1 To tickets - 1
                Cells(r + x, 1).EntireRow.Insert
                Cells(r + x, targetCol).Value = surname
            Next x
    
            LastRow = LastRow + tickets - 1
        End If
    Next r
    

    Any time that you want to insert or delete rows on a Worksheet from inside a loop, it's usually better to start at the end and work backwards. This means that you don't have to adjust your loop index in most cases

提交回复
热议问题