Get all weeknums from 2 input dates and put them in an array?

前端 未结 2 1887
后悔当初
后悔当初 2021-01-23 07:46

Since I asked a wrong question in the last post, but still improved a lot (I already created a Planning table in Excel, if someone want it I will be happy to share), here is wha

相关标签:
2条回答
  • 2021-01-23 07:59

    This is an alternative way:

    Sub Test()
    
    Dim StrtD As Long, EndD As Long
    Dim arr As Variant
    
    With Sheets("Foglio1")
        StrtD = Application.WeekNum(.Cells(1, 2).Value, 2)
        EndD = Application.WeekNum(.Cells(2, 2).Value, 2)
        arr = Application.Transpose(.Evaluate("ROW(" & StrtD & ":" & EndD & ")"))
    End With
    
    End Sub
    

    The Application.Transpose() creates an 1-D array you can call through arr(x) where x is any position within the array. You can leave the transpose if you want to create a 2-D array.


    To not use .Transpose but use .Columns to return a 1-D array you can tweak the code to:

    Sub Test()
    
    Dim StrtD As Long, EndD As Long
    Dim arr As Variant
    
    With Sheets("Foglio1")
        StrtD = Application.WeekNum(.Cells(1, 2).Value, 2)
        EndD = Application.WeekNum(.Cells(2, 2).Value, 2)
        arr = .Evaluate("COLUMN(" & .Cells(1, StrtD ).Address & ":" & .Cells(1, EndD ).Address & ")")
    End With
    
    End Sub
    

    I guess it's a matter of preference as both ways will return an array > arr(11, 12, 13, 14, 15, 16, 17)

    0 讨论(0)
  • 2021-01-23 08:20

    Using Application.WeekNum will be much more simple:

    Option Explicit
    Sub Test()
    
        Dim StartDate As Date, EndDate As Date
    
        With ThisWorkbook.Sheets("Foglio1") 'remember to fully qualify your ranges, including the workbook
            StartDate = .Range("B2")
            EndDate = .Range("B3")
        End With
    
        Dim StartWeek As Long, EndWeek As Long
        StartWeek = Application.WeekNum(StartDate, 2)
        EndWeek = Application.WeekNum(EndDate, 2)
    
        Dim arr
        Dim i As Long
        ReDim arr(StartWeek To EndWeek)
        For i = StartWeek To EndWeek
            arr(i) = i
        Next
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题