【问题标题】:Insert Rows based on DateDiff根据 DateDiff 插入行
【发布时间】:2016-08-02 01:13:00
【问题描述】:

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

我有以下代码插入行,但随后给我一个“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

【问题讨论】:

    标签: vba excel datediff


    【解决方案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
    

    请注意 cmets 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多