4

我想按天查找每个月的总天数。

例如

月份是'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 代码帮助

4

2 回答 2

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)
于 2012-01-03T12:40:40.543 回答
2

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

  1. 一个月中的天数仅一天(按YesMsgbox 提示),或
  2. 一周中的每一天的一个月中的几天(按NoMsgbox 提示)。

    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
    
于 2012-01-03T12:44:49.560 回答