excel - 通过 VBA 在 Excel 中创建可视日历
问题描述
我的程序做了我期望做的事情。我对最后一个循环不满意。
Option Explicit
Public Sub calendar()
Dim i, j
Dim mDay As Date
For i = 1 To 12
Cells(1, i + 1).Value = MonthName(i)
For j = 2 To 32
If IsDate(j - 1 & "/" & i & "/" & Year(Date)) Then
mDay = CDate(j - 1 & "/" & i & "/" & Year(Date))
Cells(j, i + 1).Value = mDay
If Weekday(mDay) = 1 Then
Cells(j, i + 1).Interior.Color = vbRed
ElseIf Weekday(mDay) = 7 Then
Cells(j, i + 1).Interior.Color = vbYellow
Else
Cells(j, i + 1).ClearFormats
End If
Cells(j, i + 1).Value = Format(mDay, "DDDD")
End If
Next j
Next I
For i = 1 To 31
Cells(i + 1, 1).Value = i
Next i
End Sub
我已经有一个计数为 31 的循环,但如果我把它放在那里,它将被执行 12 次。有更聪明的方法吗?
解决方案
我会将值分配到一个数组中,然后写入工作表 1 次,这样应该会更快。(读/写到/从单元格是昂贵的操作)
Sunday
然后对and使用条件格式Saturday
:
Public Sub calendar()
Dim i As Long, j As Long
Dim outputArr() As Variant
ReDim outputArr(1 To 32, 1 To 13) As Variant
For i = 1 To 12
outputArr(1, i + 1) = MonthName(i)
For j = 2 To 32
If IsDate(j - 1 & "/" & i & "/" & Year(Date)) Then
outputArr(j, i + 1) = Format(DateSerial(Year(Date), i, j - 1), "DDDD")
End If
Next j
Next i
For i = 1 To 31
outputArr(i + 1, 1) = i
Next i
Dim calendarRng As Range
Set calendarRng = Range("A1").Resize(32, 13)
Dim formatSunday As FormatCondition
Set formatSunday = calendarRng.FormatConditions.Add(xlCellValue, xlEqual, Formula1:="=" & Chr(34) & Format(Date - Weekday(Date, vbSunday) + 1, "DDDD") & Chr(34))
formatSunday.Interior.Color = vbRed
Dim formatSaturday As FormatCondition
Set formatSaturday = calendarRng.FormatConditions.Add(xlCellValue, xlEqual, Formula1:="=" & Chr(34) & Format(Date - Weekday(Date, vbSaturday) + 1, "DDDD") & Chr(34))
formatSaturday.Interior.Color = vbYellow
calendarRng.Value = outputArr
End Sub
推荐阅读
- python - 如何在 Django 中测试查询集
- excel - 从范围中排除多个单元格
- c# - vscode 调试 c# 应用程序
- javascript - 使用AJAX请求json类型的列表数据从chart.js动态输出到气泡图中
- mysql - 我有两个表,它们有一对多的关系,我正在尝试通过 id 从两个表中检索数据
- c++ - 当用户键入分隔符时停止 getline() 输入
- jquery - 单击时未打开折叠的 Bootstrap 导航栏
- terraform - 如何在 terraform 中修复 MalformedPolicyDocument
- python - 独立配置 pyspark 以由用户运行执行程序
- rest - Jira Cloud 通过 REST API 搜索具有多个特殊字符的问题