过渡到新月期间Excel VBA中的日期增加

时间:2018-08-10 14:36:38

标签: excel excel-vba date

 Private Sub newMonth(MonthValue As Date)
'month value is the value that is passed into it from the first data row of the old sheet

Dim isWeekend As Boolean

Dim i As Long

'is it a year shift? (december = 12, january = 1)
If Month(MonthValue) + 1 < Month(MonthValue) Then
    For i = 0 To 4
        'is the date at least 5 days in the week from sunday?

        If Weekday(Format(DateSerial(Year(MonthValue) + 1, Month(MonthValue) + 1, i + 1), "mm/dd/yyyy"), vbSunday) > 5 Then
            'put in the cells of the new sheet in the first column a date starting from the first day of the next month
            Cells(FIRST_DATA_ROW + (i * 2), 1) = Format(DateSerial(Year(MonthValue) + 1, Month(MonthValue) + 1, i + 1), "mm/dd/yyyy")
        Else
            'if its not, clear contents
            ActiveSheet.Range(Cells(FIRST_DATA_ROW + (i * 2), 1), Cells(FIRST_DATA_ROW + (i * 2), 32)).ClearContents

        End If



    Next i
'it is not a year shift, just an increment of a month
Else

   for i = 0 to 4
         If Weekday(Format(DateSerial(Year(MonthValue), Month(MonthValue) + 1, i + 1), "mm/dd/yyyy"), vbSunday) > 1 And _
            Weekday(Format(DateSerial(Year(MonthValue), Month(MonthValue) + 1, i + 1), "mm/dd/yyyy"), vbSunday) < 7 Then
            'put in the cells of the new sheet in the first column a date starting from the first day of the next month
            Cells(7 + (i * 2), 1) = Format(DateSerial(Year(MonthValue), Month(MonthValue) + 1, i + 1), "mm/dd/yyyy")
           i = i + 1
        Else
            'if its not, clear contents
            ActiveSheet.Range(Cells(FIRST_DATA_ROW + (i * 2), 1), Cells(FIRST_DATA_ROW + (i * 2), 32)).ClearContents
        End If
    Next i
End If


End Sub

问候。上面的代码有两个相关的工作表,我将它们分别称为工作表A和工作表B。它是整个时间/出勤跟踪系统的一部分,并为每个时间段创建一个新的工作表。例如,工作表A的日期为8/6-8/10,工作表B的日期为8 / 13-8 / 17。周末不包括在床单中;只有工作日。

以下函数不仅在更改星期数而且还更改几个月时被调用。因此,例如,如果工作表A具有7 / 30-7 / 31(上周的星期一和星期二),则工作表B应该具有8 / 1-8 / 3(星期三至上星期五)。

麻烦的是,无论如何,工作表B的第一个日期都应该出现在单元格中(FIRST_DATA_ROW,1),顺便说一句,FIRST_DATA_ROW =7。例如,如果工作表A在星期二结束,就会遇到问题,因为因为编写代码将使第一个日期出现在cell(11,1)中。换句话说,我需要将单元格(7,1)设置为新一周的星期一,将单元格(9,1)设置为新一周的星期二,依此类推;除非前一周在星期二结束,在这种情况下,我需要将cell(7,1)设置为新周的星期三,将cell(9,1)设置为新周的星期四,并使用cell(11,1 )作为新一周的星期五,并且由于下一个值为周末,因此代码在此之后终止。

0 个答案:

没有答案