我有一个电子表格,用于跟踪我的课程。我需要将其设置为导出到日历中。我列出了所有课程的开始和结束日期。我希望能够使用日期差异作为行数在每个列出的类下面插入行,然后将信息复制到具有相应日期的那些行。
我有以下代码插入行,但后来给了我一个' 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
答案 0 :(得分:1)
您收到此错误,因为列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
请注意评论以获取更多信息。