如何获得一个月的总日数

时间:2012-01-03 11:51:51

标签: count vb6 days

我希望按天计算每月总天数。

例如

月份为'01/2011'(mm / yyyy)

Expected Output

Sunday - 5
Monday - 5
Tuesday - 5
Wednesday - 4
Thursday - 4
Friday - 4
Saturday - 4

尝试代码

Dim lngCnt As Long
    Dim strOut As String
    dtStart = DateValue('01/2012')
    dtEnd = DateAdd("d", DateDiff("d", '01/2012', DateAdd("m", 1, '01/2012') - 1), dtStart)
    lngCnt = Weekday(dtStart) - 3
    Do
        lngCnt = lngCnt + 3
        strOut = strOut & Format(lngCnt, "00") & ","
    Loop While lngCnt + 3 <= dtEnd - dtStart

上述代码会将结果显示为Wednesday = 4, 11, 18, 25

但我希望像这样wednesday = 4'总计数

如何在vb6中完成

需要VB6代码帮助

2 个答案:

答案 0 :(得分:3)

这是一个你可以打电话的功能

它需要两个参数(年和月)并返回一个数组(1到7),表示该月的星期日到星期六天数

Function Days(yr As Long, mn As Long) As Variant
    Dim First As Date
    Dim FirstDay As Long
    Dim DaysInMonth As Long
    Dim DayCount(1 To 7) As Long
    Dim i As Long

    DayCount(1) = 4
    DayCount(2) = 4
    DayCount(3) = 4
    DayCount(4) = 4
    DayCount(5) = 4
    DayCount(6) = 4
    DayCount(7) = 4

    First = DateSerial(yr, mn, 1)
    DaysInMonth = DateSerial(yr, mn + 1, 1) - First
    FirstDay = Weekday(First)
    For i = FirstDay To DaysInMonth + FirstDay - 28 - 1
        DayCount((i - 1) Mod 7 + 1) = 5
    Next

    Days = DayCount
End Function

<强>更新

使用它来获取一个月内的星期五数量,使用

Fridays = Days(2012, 2)(6)  ' For Fridays in Fedruary 2012

更新2:

采取Brettdj的建议

要返回“Fridays = 4”之类的字符串,请使用

Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")(6) & " = " & Days(2012, 2)(6)

答案 1 :(得分:2)

更新了答案 更新了您的评论以返回

  1. 仅限一天的一个月内的日期(在Msgbox提示下按Yes)或
  2. 一周中每个月的天数(在Msgbox提示下按No)。

    Sub GetDay()  
    Dim strMonth As String  
    Dim strOut As String  
    Dim lngDay As Long  
    Dim lngCheck As Long  
    
    strMonth = "01/2012"
    
    lngCheck = MsgBox("Press Yes to run single day" & vbNewLine & "Press No to run the entire week", vbYesNoCancel, "User choice")
    
    If lngCheck = vbCancel Then Exit Sub
    
    If lngCheck = vbYes Then
    'Option 1 one day
    lngDay = vbFriday
    strOut = strOut & DaysInMonth(lngDay, strMonth) & vbNewLine
    Else
    'Option 2 all days
    For lngDay = vbSunday To vbSaturday
    strOut = strOut & DaysInMonth(lngDay, strMonth) & vbNewLine
    Next
    End If
    
    MsgBox strOut
    End Sub
    
    Function DaysInMonth(ByVal lngDay, ByVal strMonth)
    Dim dtStart As Date
    Dim dtEnd As Date
    Dim dtTest As Date
    Dim lngCnt As Long
    Dim i As Long
    
    dtStart = DateValue(strMonth)
    dtEnd = DateAdd("d", DateDiff("d", strMonth, DateAdd("m", 1, strMonth) - 1), dtStart)
    lngCnt = (dtEnd - dtStart + 1)
    
    DaysInMonth = WeekdayName(lngDay, , vbSunday) & " - 4"
    
    For i = 1 To lngCnt Mod 7
    If Weekday(DateAdd("d", i - 1, dtStart)) = lngDay Then
     DaysInMonth = WeekdayName(lngDay, , vbSunday) & " - 5"
    Exit For
    End If
    Next
    
    End Function