Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 具有可变结尾整数的For循环_Vba_Excel - Fatal编程技术网

Vba 具有可变结尾整数的For循环

Vba 具有可变结尾整数的For循环,vba,excel,Vba,Excel,我有一个包含40000行数据的数据集。设置“我的代码”是为了检查第n+1行中的日期是否比第n行中的日期晚1天。如果第n行和第n+1行中的日期没有按照正常的时间顺序排列,则会添加一行,其中包含该日期的空白数据 我的问题是,因为我在添加行,所以我不知道for循环的结束范围应该是什么。我还尝试设置一个非常大的范围,比如“n=2到50000”。但这给了我一个溢出错误 这是我的密码: Sub MissingDates() Dim n As Integer Worksheets("sheet1").Ac

我有一个包含40000行数据的数据集。设置“我的代码”是为了检查第n+1行中的日期是否比第n行中的日期晚1天。如果第n行和第n+1行中的日期没有按照正常的时间顺序排列,则会添加一行,其中包含该日期的空白数据

我的问题是,因为我在添加行,所以我不知道for循环的结束范围应该是什么。我还尝试设置一个非常大的范围,比如“n=2到50000”。但这给了我一个溢出错误

这是我的密码:

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
submissingdates()
作为整数的Dim n
工作表(“表1”)。激活
对于n=2到40000
如果单元格(n,2)。值单元格(n+1,2)。则值为-1
单元格(n+1,2).EntireRow.Insert Shift:=xlShiftDown
单元(n+1,2)=单元(n,2)+1
如果结束
下一个
端接头

提前感谢您的帮助。

溢出错误是因为您将
n声明为整数(即32767),但将其推到40000。您可以通过将
n声明为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

n=2'有符号整数不能达到40000,您应该自下而上工作

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

Dim n只要长
For n=单元格(rows.coun,“B”)。结束(xlup)。第1到2行步骤1
我喜欢将最后一行合并到For n循环中的方式,您能解释一下For m循环如何比较值吗,我认为这与“To”有关。谢谢,这非常有效。我也很好奇“To”是如何用来比较m值的。我不知道“To”可以用这种方式。日期只是数字。对于m=。。。到只需从一个日期到下一个日期,填写任何缺失的日期。如果日期是连续的,则数学根本不进入For循环。