用vba写一段代码,在EXCEL表中生成一个2025年日历
时间: 2024-10-22 14:10:27 浏览: 87
一个简单的表格VBA日历窗体
在Excel中使用VBA生成2025年日历的代码如下:
```vba
Sub GenerateCalendar()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add
ws.Name = "2025年日历"
Dim i As Integer, j As Integer
Dim startDate As Date
startDate = DateSerial(2025, 1, 1)
' 设置标题行
ws.Cells(1, 1).Value = "星期日"
ws.Cells(1, 2).Value = "星期一"
ws.Cells(1, 3).Value = "星期二"
ws.Cells(1, 4).Value = "星期三"
ws.Cells(1, 5).Value = "星期四"
ws.Cells(1, 6).Value = "星期五"
ws.Cells(1, 7).Value = "星期六"
' 计算2025年1月1日是星期几
Dim firstDayOfWeek As Integer
firstDayOfWeek = Weekday(startDate)
' 填充日期
Dim currentRow As Integer
currentRow = 2
For i = 1 To 12 ' 月份循环
Dim daysInMonth As Integer
daysInMonth = Day(DateSerial(2025, i + 1, 0)) ' 获取当前月的天数
' 设置月份标题
ws.Cells(currentRow, 1).Value = MonthName(i) & "月"
ws.Cells(currentRow, 1).Font.Bold = True
ws.Cells(currentRow, 1).HorizontalAlignment = xlCenter
ws.Cells(currentRow, 1).VerticalAlignment = xlCenter
' 定位到该月第一天对应的列
Dim dayColumn As Integer
dayColumn = firstDayOfWeek
' 填充该月的每一天
For j = 1 To daysInMonth
ws.Cells(currentRow + (j - 1) \ 7 + 1, dayColumn).Value = j
dayColumn = dayColumn + 1
If dayColumn > 7 Then
dayColumn = 1
End If
Next j
' 更新下一个月的起始列为当前行的下一个位置
currentRow = currentRow + Int((daysInMonth + firstDayOfWeek - 1) / 7) + 1
firstDayOfWeek = dayColumn
Next i
' 自动调整列宽
ws.Columns("A:G").AutoFit
End Sub
```
这段代码首先创建一个新的工作表,并命名为“2025年日历”。然后,它设置了一周的标题,并计算了2025年1月1日是星期几。接着,代码通过循环每个月,并在相应的单元格中填入日期。最后,它自动调整了列宽以适应内容。
阅读全文