Excel VBA需求:生成2023年非周日日期并调整行间距
修改Excel VBA代码实现特定日期写入需求
我来帮你调整VBA代码,精准实现你想要的规则:从2023年1月1日到12月31日写入日期,格式为dd, mm, yyyy,跳过所有周日,并且周六到周一之间只留3行间隔(其他日期间隔8行)。
先看修改后的完整代码:
Sub Datesoftheyear() Dim currentDate As Date Dim endYear As Date Dim currentRow As Integer Dim nextRowStep As Integer ' 初始化起始日期为2023年1月1日,结束日期为2023年12月31日 currentDate = DateSerial(2023, 1, 1) endYear = DateSerial(2023, 12, 31) currentRow = 1 ' 从第一行开始写入 Do While currentDate <= endYear ' 跳过所有周日(Weekday函数返回1代表周日) If Weekday(currentDate, vbSunday) <> 1 Then ' 写入指定格式的日期 Cells(currentRow, 1).Value = Format(currentDate, "dd, mm, yyyy") ' 判断当前日期是否为周六,决定下一行的间隔 If Weekday(currentDate, vbSunday) = 7 Then nextRowStep = 3 ' 周六到周一间隔3行 Else nextRowStep = 8 ' 其他日期间隔8行 End If currentRow = currentRow + nextRowStep End If ' 推进到下一天 currentDate = DateAdd("d", 1, currentDate) Loop End Sub
关键修改点说明:
- 固定起始日期:把原来的
currentDate = Date改成DateSerial(2023, 1, 1),确保从2023年元旦开始,而不是当前系统日期。 - 跳过周日:用
Weekday(currentDate, vbSunday) <> 1判断,只要是周日就跳过不写入。 - 动态调整行间距:通过判断当前日期是否为周六(
Weekday(currentDate, vbSunday) = 7),决定下一次写入的行间隔是3还是8。 - 循环逻辑优化:改用
Do While循环,更直观地控制日期范围,避免原代码中X未定义的问题。
这样运行代码后,就能完全符合你想要的日期排布规则啦!
内容的提问来源于stack exchange,提问作者Divad
相关产品推荐
相关产品推荐

