基于DateDiff插入行

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

我有下面的代码插入行,但然后给我一个'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(可能两者)不包含date和DateDiff失败。

这发生在插入几行然后移动到下一行时。 当然,新插入的行是空的,并且不包含B列或D列中的date(并且发生上述错误)。

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

 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 

注意更多信息的评论。