Excel VBA将日期设置为最近的一天,有没有更好的方法?

ukxgm1gy  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(190)

Recently I needed to set some dates in Excel to the nearest Wednesday for a scheduling process. I found some answers here in stackoverflow and other sites but none were giving the desired result at all times. So, I wrote a little sub to achieve this for any day you need, but it got me wondering if there was a better way to achieve this, if not then I hope you find it helpful.

EDIT: This sub is part of a large process run by a macro by clicking a custom ribbon button, the input dates come from an array, therefore, I have to use vba to change them.

Here is the matrix with results:

And the code is this:

Sub SetNextWed()

    Range("A6").Activate
    Do Until ActiveCell.Value = ""
        SetToNextDate ActiveCell.Value, vbWednesday, 2
        ActiveCell.Offset(1, 0).Activate
    Loop
End Sub

Sub SetToNextDate(MyDate As Date, DayOfWeek As Integer, Column As Integer)
    Dim dNext_Wednesday As Date

    dNext_Wednesday = MyDate

    Select Case Weekday(MyDate)
        Case DayOfWeek
            dNext_Wednesday = MyDate
        Case Else
            dNext_Wednesday = MyDate + DayOfWeek - Weekday(MyDate)
            If MyDate > dNext_Wednesday Then
                dNext_Wednesday = MyDate + ((DayOfWeek + 7) - Weekday(MyDate))
            End If
    End Select

I've tried this solutions:
https://vbaf1.com/date-time/next-wednesday-date/https://www.mrexcel.com/board/threads/determine-date-of-next-and-most-recent-monday-vba.983467/How do I find out what the Date is for Next Saturday or the current Saturday?

2skhul33

2skhul331#

在Excel中,日期只是数字,日期数字以7为模表示星期几,0表示星期六,6表示星期五。因此不需要VBA。下面的单元格公式计算所需的星期三日期:=7*INT((A1+2)/7)+4,假设原始日期在A1中。

相关问题