For loop with variable ending integer

时间:2018-03-25 21:16:14

标签: excel vba excel-vba

I have a dataset of 40,000 rows of data. My code is set so that it checks if the date in row n+1 is 1 day after the date in row n. If the dates in rows n and n+1 do not follow in normal chronological order, then it adds a row with blank data for that date.

My issues is that because I am adding rows along as I go, I have no idea what the ending range my for loop should have. I also tried just setting a really large range like "For n = 2 to 50000". But this gives me an overflow error.

Here is my code:

Sub MissingDates()

Dim n As Integer

Worksheets("sheet1").Activate

For n = 2 To 40000
       If Cells(n, 2).Value <> Cells(n + 1, 2).Value - 1 Then
            Cells(n + 1, 2).EntireRow.Insert Shift:=xlShiftDown
            Cells(n + 1, 2) = Cells(n, 2) + 1
       End If
Next

End Sub

Thank you in advance for any help.

2 个答案:

答案 0 :(得分:4)

有符号整数不会达到40,000,你应该从下往上工作。

Option Explicit

Sub MissingDates()
    Dim n As Long, m As Long

    With Worksheets("sheet1")
        For n = .Cells(.Rows.Count, "B").End(xlUp).Row - 1 To 2 Step -1
            For m = .Cells(n + 1, "B").Value2 - 1 To .Cells(n, "B").Value2 + 1 Step -1
                .Cells(n + 1, 2).EntireRow.Insert Shift:=xlShiftDown
                .Cells(n + 1, 2) = m
            Next m
        Next n
    End With

End Sub

答案 1 :(得分:3)

出现溢出错误的原因是您声明了n As Integer(即32,767),但是将其推送到40,000。您可以通过声明n As Long来解决此问题。

至于您的问题,您更希望使用While循环而不是For循环。看起来应该是这样的:

n = 2 '<- your starting value
Do While Cells(n+1,2).Value <> "" '<-- I guess you stop when there's no more value in your row
       If Cells(n, 2).Value <> Cells(n + 1, 2).Value - 1 Then
            Cells(n + 1, 2).EntireRow.Insert Shift:=xlShiftDown
            Cells(n + 1, 2) = Cells(n, 2) + 1
       End If
       n = n + 1 '<-- increment n 
Loop