Public Function DaysOfMonth(Year As Long, Month As Long) As Long
Dim Day1 As String, Day2 As String
Day1 = CStr(Year) + "-" + CStr(Month) + "-1"
Day2 = CStr(Year) + "-" + CStr(Month + 1) + "-1"
DaysOfMonth = DateDiff("d", Day1, Day2)
End Function
Public Function DaysOfMonth(aYear As Integer, aMonth As Integer) As Integer
Dim i As Integer
For i = 31 To 28 Setp -1
If IsDate(CStr(aYear) & "-" & CStr(aMonth) & "-" & i) Then
DaysOfMonth = i
Exit Function
End If
Next
End Function
呵呵!还有一种方法的
Public Function DaysOfMonth(aYear As Integer, aMonth As Integer) As Integer
For i = 1 To 31
ine = IsDate(CStr(aYear) & "-" & CStr(aMonth) & "-" & i)
If ine = False Then
DaysOfMonth = i - 1
Exit Function
End If
Next
If ine = True Then DaysOfMonth = i - 1
End Function
to huntout:
ok!您的写法确实省去了不少不必要的循环。非常好!!
我是从以前作的打印月每天报表的程序中摘录的,思路被以前的需求束缚了,所以对于返回天数就没想到能进行优化。
呵呵!用下面的语句判断也可以:
Public Function DaysOfMonth(aYear As Integer, aMonth As Integer) As Integer
On Error Resume Next
For i = 31 To 28 Step -1
y = Month(CStr(aYear) & "-" & CStr(aMonth) & "-" & i)
If y = aMonth Then
DaysOfMonth = i
Exit Function
End If
Next
End Function
Public Function DaysOfMonth(Year As Integer, Month As Integer)
Dim Day1, Day2 As String
Day1 = CStr(Year) + "-" + CStr(Month) + "-1"
Day2 = CStr(Year) + "-" + CStr(Month + 1) + "-1"
DaysOfMonth = DateDiff("d", Day1, Day2)
End Function
Public Function DaysOfMonth(Year As Integer, Month As Integer)
Dim Day1, Day2 As String
Day1 = CStr(Year) + "-" + CStr(Month) + "-1"
Day2 = CStr(Year) + "-" + CStr(Month + 1) + "-1"
DaysOfMonth = DateDiff("d", Day1, Day2)
End Function
我认为最简单的办法就是:
用下一个第一天减1就可以得到本月最后一天,比如要算8月份的天数,就以9月1日减1得到8月份31日,那么8月就是31天。
Dim vDate As Date
Dim mm, yy, dd As Integer
yy = Year(Date)
mm = Month(Date)
If mm = 12 Then
yy = yy + 1
mm = 1
Else
mm = mm + 1
End If
vDate = DateSerial(yy, mm, 1) - 1
dd = Day(vDate)