试图创建一个循环来查找缺少的日期

时间:2016-03-10 09:21:16

标签: excel excel-vba vba

我有一些代码可以在我的开始(J2)和结束日期(K2)之间创建缺少日期。我有一个大约6000人的列表,其中包含开始日期和结束日期,并希望重复每行的代码。

有人知道如何循环吗?

mysql-data-input.xml

2 个答案:

答案 0 :(得分:1)

假设您的名单列表中的开始日期和结束日期位于JK列中,那么快速更改您的代码(如下所示)应该可以解决问题

Sub FindMissingDates()
    Dim r As Long
    Dim FirstDate As Date
    Dim LastDate As Date
    Dim NextDate As Date
    Dim DateOffset As Range
    Dim DateIter As Date

    For r = 2 To ActiveSheet.Cells(Rows.Count, "J").End(xlUp).Row '<~~ Loop each row
        FirstDate = ActiveSheet.Cells(r, "J").Value
        LastDate = ActiveSheet.Cells(r, "K").Value
        Set DateOffset = ActiveSheet.Cells(r, "M")

        For DateIter = FirstDate To LastDate
            DateOffset.Value = DateIter
            Set DateOffset = DateOffset.Offset(0, 1)
        Next DateIter
    Next r

End Sub

答案 1 :(得分:0)

您可以添加另一个For循环。

Dim sht As Wokrsheet
Dim LastRow As Integer
Dim FirstDate As Date
Dim LastDate As Date
Dim NextDate As Date
Dim DateOffset As Range
Dim DateIter As Date
Dim i As Integer

Set sht = ThisWorkbook.Worksheets("Name of your sheet")
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

FirstDate = Range("J2").Value
LastDate = Range("K2").Value
Set DateOffset = Range("M2")

For i = First row of data To LastRow - 1 
   For DateIter = FirstDate To LastDate
       DateOffset.Value = DateIter
       Set DateOffset = DateOffset.Offset(i, 1)
   Next DateIter
Next i

看看这对你有用吗?