根据 DateDiff 插入行

Insert Rows based on DateDiff

我有一个电子表格,用于跟踪我的 classes。我需要将其设置为导出到日历中。我的所有 classes 都列出了开始日期和结束日期。我希望能够使用日期差异作为行数在每个列出的 class 下面插入行,然后将信息复制到具有相应日期的那些行。

我有以下插入行的代码,但随后出现“1004”错误。

Public Sub Format()
    Dim i As Long
    Dim d As Long

    LastRow = Worksheets("GCalExport").UsedRange.Rows.Count

    For i = 2 To LastRow
        d = DateDiff("d", Cells(i, "B"), Cells(i, "D"))
        Cells(i, 1).Offset(1).Resize(d).EntireRow.Insert
    Next i
End Sub

您收到此错误是因为 B 列或 D 列(可能两者)不包含日期并且 DateDiff 失败。

当您插入几行然后移动到下一行时,就会发生这种情况。当然,新插入的行是空的,不包含B列或D列的日期(并出现上述错误)。

所以,你需要调整你的代码如下:

Public Sub Format()

Dim i As Long
Dim d As Long
Dim LastRow As Long

With Worksheets("GCalExport")
    LastRow = .UsedRange.Rows.Count
    i = 2

    While i <= LastRow
        'Check if column B and column D actually contain a date
        If IsDate(.Cells(i, "B")) And IsDate(.Cells(i, "D")) Then
            d = DateDiff("d", .Cells(i, "B"), .Cells(i, "D"))
            .Cells(i, 1).Offset(1).Resize(d).EntireRow.Insert
            'Since you inserted d rows the next row to check is
            '  row i + d
            i = i + d
            '  furthermore the last row just got increased by
            '  d as well
            LastRow = LastRow + d
            'Move to the next row for processing
            i = i + 1
        Else
            'If column B and / or D do not contain a valid date then
            '  ignore that row and go to the next row.
            i = i + 1
        End If
    Wend
End With

End Sub

注意评论以获取更多信息。