如何为n行更新日期n次?

时间:2018-04-05 09:02:27

标签: excel vba excel-vba excel-2010 excel-2007

我目前正在处理16 000行excel文件

  • B列是我要更​​新的日期
  • H列是开始日期
  • 第I列是结束日期
  • 列K是需要更新日期的次数(在n行上更新)

我们的想法是在B列显示从开始日期到结束日期的所有日期(每列一个日期)。

您可以在我当前的代码下面找到。我是初学者,可能包含很多错误。能不能给我一些帮助,我不断收到小错误:91,1004,5 ...

Sub Dates()
    Dim i As Long
    Dim k As Long
    Dim MyDate As Long
    Dim EndDate As Long
    Dim EndRowA As Long
    Dim EndRowB As Long
    Dim EndRowH As Long
    Dim StartDate As Long
    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")

    StartDate = ws.Cells(ws.Rows.Count, "H").Value
    MyDate = ws.Cells(ws.Rows.Count, "B").Value
    EndDate = ws.Cells(ws.Rows.Count, "I").Value
    EndRowA = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    EndRowB = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
    EndRowH = ws.Cells(ws.Rows.Count, 8).End(xlUp).Row

    Do While (i <= EndRowH And i <= EndRowA And i <= EndRowB)
        If ws.Cells(i, "H").Value = ws.Cells(i, "I").Value Then
            GoTo Continue
        ElseIf ws.Cells(i, "H").Value = ws.Cells(i, "I").Value Then
            For k = 1 To ws.Cells(i, k).Value
                ws.Cells(i + 1, "B").Select
                ws.Cells(i, "B").Value = ws.Cells(i - 1, "H").Value + 1
            Exit For
Continue:
        Next k
    End If
Loop
End Sub

电子表格中的主要列应如下所示:

Type    Date     Start date   End Date   #

A   01/01/2018  01/01/2018  01/10/2018  10
A   01/02/2018  01/01/2018  01/10/2018  10
A   01/03/2018  01/01/2018  01/10/2018  10
A   01/04/2018  01/01/2018  01/10/2018  10
A   01/05/2018  01/01/2018  01/10/2018  10
A   01/06/2018  01/01/2018  01/10/2018  10
A   01/07/2018  01/01/2018  01/10/2018  10
A   01/08/2018  01/01/2018  01/10/2018  10
A   01/09/2018  01/01/2018  01/10/2018  10  
A   01/10/2018  01/01/2018  01/10/2018  10
B   02/06/2018  02/06/2018  02/10/2018  5
B   02/07/2018  02/06/2018  02/10/2018  5
B   02/08/2018  02/06/2018  02/10/2018  5
B   02/09/2018  02/06/2018  02/10/2018  5
B   02/10/2018  02/06/2018  02/10/2018  5

我提前感谢你

1 个答案:

答案 0 :(得分:2)

只需尝试此代码,您就会看到正在犯的错误:

Sub Dates()
    Dim ws As Worksheet
    Dim i As Long
    Dim k As Long
    StartDate = ws.Cells(ws.Rows.Count, "H").Value
    Date = ws.Cells(ws.Rows.Count, "B").Value
    EndDate = ws.Cells(ws.Rows.Count, "I").Value
    EndRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

    MsgBox ws.Cells(ws.Rows.Count, "H").Address
    MsgBox ws.Cells(ws.Rows.Count, "B").Address

End Sub

我猜你在“H”栏的最后一行没有任何价值。这是$H$1048576。 一般来说,EndRowEnd(xlUp)一起传递的方式是一个不错的选择,尝试在任何地方模仿它。

一些改进意见:

  • 在模块顶部写Option Explicit。它会强制您声明变量并在执行前进行快速检查。
  • 您应该将ws分配给工作表。最简单的方法是Set ws = Worksheets("NameOfTheWorksheet")
  • 你正在做的循环应该以预期的方式结束。例如,对于每个Do While,应该写一个Loop"Do While" "Loop" and "While" "Wend" Loop. What's the difference?
  • {li> GoTo语句VBA中的语句仅适用于句子On Error GoTo ErrHandler。通常,如果从代码中删除GoTo Continue,它仍会避免第二次循环。