Vba Excel写入一年中的日期(星期日除外)

irtuqstp  于 2023-01-18  发布在  其他
关注(0)|答案(3)|浏览(209)

我想写一个Excel的Vba,允许我每8行写一次从2023年1月开始到2023年12月底的日期(格式dd,mm,yyyy),不包括所有星期的星期日。如果我想减少唯一的行的距离,那就把星期六和星期一分开,我该怎么做?附上一个Example
到目前为止,我写了这个例程,写一年中的每一天,但它也考虑到星期天和8行的距离从星期六到星期一,我想减少到3行,如前所述。谢谢

Sub Datesoftheyear()

Dim currentDate As Date
Dim endYear As Date

currentDate = Date
endYear = DateSerial(Year(Now()), 12, 31)
For i = 1 To X Step 8
    Cells(i, 1).Value = Format(currentDate, "dd-mm-yyyy")
    currentDate = DateAdd("d", 1, currentDate)
    If currentDate > endYear Then Exit For
Next i

End Sub
np8igboo

np8igboo1#

您可以使用Weekday函数或将DatePart函数与Interval:="w"配合使用来确定日期是否为Sunday
然后,在循环中,可以测试currentDate是否为星期天,如果是,则向前推进一天。

Sub Datesoftheyear()

    Dim currentDate As Date
    Dim endYear As Date
    
    currentDate = Date
    endYear = DateSerial(Year(Now()), 12, 31)
    For i = 1 To X Step 8
        Cells(i, 1).Value = Format(currentDate, "dd-mm-yyyy")
        currentDate = DateAdd("d", 1, currentDate)
        
        'If sunday, advance to next day
        If Weekday(currentDate) = vbSunday Then currentDate = DateAdd("d", 1, currentDate)
        
        If currentDate > endYear Then Exit For
    Next i

End Sub
ogq8wdun

ogq8wdun2#

您可以使用此代码。

  • 偏移量在子函数的开头被定义为常量,这样您就可以更改它,而不需要在代码中搜索。
  • 我添加了一个显式的activesheet.cells(1,1)-您可能需要调整它
  • 我将开始日期设置为当前年份的1月1日。
  • 关于“星期天”检查:你必须根据你的地区设置来调整。对于德国,一周从周一和周日开始工作日= 7...
Sub DatesOfTheYear()

'Define row offset between two dates here
Const rowOffset As Long = 3

Dim startDate As Date, endYear As Date, rowDate As Date

Dim i As Long, j As Long

startDate = DateSerial(Year(Now()), 1, 31)
endYear = DateSerial(Year(Now()), 12, 31)

Dim rg As Range
Set rg = ActiveSheet.Cells(1, 1)

For i = 0 To DateDiff("d", startDate , endYear)
    rowDate = startDate + i

    '!!!! 
    '!!! you have to check this for your country settings
    '!!!!!
 
    If Weekday(rowDate, vbMonday) <> 7 Then
        rg.Offset(j * (rowOffset + 2)) = Format(rowDate, "ddd")
        rg.Offset((j * (rowOffset + 2)) + 1) = rowDate
        j = j + 1
    End If
    
Next i

End Sub
gkl3eglg

gkl3eglg3#

Sub Datesoftheyear()

MyRow = 1
For idt=date To DateSerial(Year(date),12,31)
    If mod(idt,7)<>1 Then
        Cells(MyRow,1).Value = idt
        MyRow = MyRow + 8
    End If
Next idt

End Sub

相关问题