Generating a list of dates given the start and end dates

前端 未结 2 1809
余生分开走
余生分开走 2021-01-20 05:59

Previously I found some VBA code done by Andy Brown that generates a list and makes each date the first or 15th for another user. I have tried to adjust this code to my need

相关标签:
2条回答
  • 2021-01-20 06:21

    Avoid using select in code it is very inefficient :)

    Sub p()
    Dim FirstDate As Date
    Dim LastDate As Date
    Dim NextDate As Date
    Dim r As Long
    FirstDate = Range("A1").Value
    LastDate = Range("a2").Value
    r = 1
    Do
     FirstDate = FirstDate + 1
     Cells(r, 2) = FirstDate
     r = r + 1
    Loop Until FirstDate = LastDate
    End Sub 
    

    to do it in a row replace cells(r,2) by cells(1, r) and start r=2

    0 讨论(0)
  • 2021-01-20 06:22

    EDIT:

    This is apparently what you need, as discussed in comments.

    Sub GenerateDates()
    
    Dim FirstDate As Date
    Dim LastDate As Date
    Dim NextDate As Date
    
    FirstDate = Range("startdate").Value
    LastDate = Range("enddate").Value
    
    NextDate = FirstDate
    Range("tripdays").Select
    'selection of columns within one row
    Do Until NextDate > LastDate
    
        ActiveCell.Value = NextDate
        ActiveCell.Offset(1, 0).Select
        NextDate = NextDate + 1
    
    Loop
    
    End Sub
    

    Alternatively, a For loop would do just as well.

    Screenshot:

    enter image description here

    FURTHER EDIT:

    Horizontal version, as requested.

    Sub GenerateDatesH()
    
    Dim FirstDate As Date
    Dim LastDate As Date
    Dim NextDate As Date
    Dim DateOffset As Range
    Dim DateIter As Date
    
    FirstDate = Range("startdate").Value
    LastDate = Range("enddate").Value
    Set DateOffset = Range("tripdays")
    
    For DateIter = FirstDate To LastDate
        DateOffset.Value = DateIter
        Set DateOffset = DateOffset.Offset(0, 1)
    Next DateIter
    
    End Sub
    

    Screenshot:

    enter image description here

    Note: I've also fixed the vertical version to stop at the end date provided.

    0 讨论(0)
提交回复
热议问题