【问题标题】:For loop with variable ending integer具有可变结束整数的 For 循环
【发布时间】:2018-09-09 17:06:45
【问题描述】:

我有一个包含 40,000 行数据的数据集。我的代码设置为检查第 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

提前感谢您的帮助。

【问题讨论】:

  • Dim n As longFor n = cells(rows.coun, "B").end(xlup).row - 1 To 2 step-1

标签: vba excel


【解决方案1】:

有符号整数未达到 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

【讨论】:

  • 我喜欢你如何将最后一行合并到 For n 循环中,你能解释一下 For m 循环如何比较值,我认为它与“To”有关。
  • 谢谢您,这非常有效。我也很好奇“To”是如何比较 m 值的。我不知道“To”可以这样使用。
  • 日期只是数字。 For m = ... to ... 只是从一个日期到下一个日期工作,填写任何缺失的日期。如果日期是连续的,则数学根本不会进入 For 循环。
【解决方案2】:

溢出错误的出现是因为您声明了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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多