excel 从工作表区域中提取日期的星期几

qqrboqgw  于 2023-01-31  发布在  其他
关注(0)|答案(2)|浏览(135)

我正在编写一个月度报表宏,它需要我从一个范围中提取天数和月份数,并获得最大天数(例如1,5,7,9)以进行下一步。我有一个代码,似乎不是一个理想的解决方案。
例如,我从范围A1:A4中提取日期,尽管在编写真实的代码时,日期是从A1到最后一行。
A1= 2022年12月10日A2= 2020年14月6日A3= 2020年3月3日A4= 2021年1月4日
请注意,Excel范围中的日期惯例是英国惯例(dd/mm/yyyy)。同样,我也需要提取月份,但如果我可以获得天的代码,那么也可以获得月份的代码。*

Sub TestR1()
    Dim MonthArray(1 To 4) As Variant
    Dim x As Double
    Dim i As Byte
    Dim Rng As Range
    Dim ExDate As Date
    Dim Mx As Long
   
    Set Rng = Range("A1:A4")
             
         
    For i = 1 To 4
    Set Rng = Range("A" & i)
    ExDate = VBA.CDate(Range("A" & i).Value)
    x = VBA.Day(ExDate)
           
    MonthArray(i) = x
    Next i
   
    Mx = Excel.WorksheetFunction.Max(MonthArray)
   
    End Sub
nxagd54h

nxagd54h1#

这段代码和你的解释非常混乱。我认为你试图为每一行获取一个月和日的数组,但你的代码是:
1.从单个单元格阅读日期,而不是一行四个单元格。
1.提取该单个日期的日部分;
1.将日期值插入一个名为MonthArray的数组。
如果我没理解错的话,我会这么做:

Sub ParseDates(src As Range)
    Dim dates() As Variant
    dates = src.Value

    Dim rCount As Long
    rCount = src.Rows.Count

    Dim cCount As Long
    cCount = src.Columns.Count

    Dim days() As Variant
    Dim months() As Variant
    Dim dt As Date

    Dim r As Long, c As Long
    For r = 1 To rCount
        For c = 1 To cCount
            dt = CDate(dates(r, c))
            days(r, c) = Day(dt)
            months(r, c) = Month(dt)
        Next c
    Next r

    ... ' Whatever you want to do with your values.
End Sub
omhiaaxx

omhiaaxx2#

浸提天数和月数

Option Explicit

Sub TestR1()
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
    
    Dim rg As Range
    Set rg = ws.Range("A2", ws.Cells(ws.Rows.Count, "A").End(xlUp))
    Dim rCount As Long: rCount = rg.Rows.Count
    
    Dim Data()
    If rCount = 1 Then
        ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
    Else
        Data = rg.Value
    End If
    
    Dim Months() As Long: ReDim Months(1 To rCount)
    Dim Days() As Long: ReDim Days(1 To rCount)
    
    Dim r As Long
    
    For r = 1 To rCount
        Days(r) = Day(Data(r, 1))
        Months(r) = Month(Data(r, 1))
    Next r
    
    Debug.Print "Index", "Day", "Month"
    
    For r = 1 To rCount
        Debug.Print r, Days(r), Months(r)
    Next r
    
    Debug.Print "Max Day", "Max Month"
    Debug.Print Application.Max(Days), Application.Max(Months)

End Sub

立即窗口中的结果(Ctrl+G

Index         Day           Month
 1             20            4 
 2             16            2 
 3             27            2 
 4             15            3 
 5             26            1 
 6             4             12 
 7             3             2 
 8             26            1 
 9             20            4 
Max Day       Max Month
 27            12

相关问题