要求:
- 要在文本框
txtDate
顯示機器
- 之日起計算的
txtDate
月份週五或週四的數量,直到機器
- 之日起顯示在文本框
txtWeek
週五或週四的數量按照前一點
個假設:
- 含有程序的工作簿的
Sheet1
有兩個TextBoxes
和一個ComboBox
- 該程序將由
ComboBox
的變化事件,觸發當用戶選擇工作日來算
將此程序複製到代碼模塊Sheet1
- 更改組合框的事件
Private Sub CmbBox1_Change()
Dim sWkDy As String
Dim dDte1 As Date
Dim bDayC As Byte
Dim bThu As Boolean, bFri As Boolean
Rem Set Weekday
sWkDy = Me.CmbBox1.Value
Select Case sWkDy
Case "Thursday": bThu = True
Case "Friday": bFri = True
Case Else: Exit Sub
End Select
Rem Set First date of the current month
dDte1 = 1 + WorksheetFunction.EoMonth(Date, -1)
Rem Counts the weekdays
bDayC = Dte_Days_Count_To_Today(dDte1, blThu:=bThu, blFri:=bFri)
Rem Set Current Date in `txtDate`
'Using format `mmm-dd-yyyy` to ease reading of the date independently of the format (American or International)
Me.TxtDate.Value = Format(Date, "mmm-dd-yyyy") 'change as required
Rem Set count of weekdays `txtWeek`
'Using this format to directly show the weekdays counted
Me.TxtWeek.Value = "Count of " & sWkDy & "s: " & bDayC 'change as required
End Sub
複製標準模塊中的這些程序
'Ensure these Keywords are at the top of the module
Option Explicit
Option Base 1
此過程設置的可用選項中Combobox
- 運行此第一,需要運行一次
Private Sub CmbBox1_Set()
Dim aWkDys As Variant
aWkDys = [{"Thursday", "Friday"}]
With Me.CmbBox1
.ColumnCount = 1
.List() = aWkDys
End With
End Sub
此函數計算da的數量ys從輸入日期dDteInp
輸入日期到機器的實際日期TODAY
。結果是使用算術演算生成的,避免循環遍歷範圍中的每個日期。這也給了一次如計算各種平日的選項:從給定的日期算週四和週五到今天這樣Call Dte_Days_Count_To_Today(dDteInp, blThu:=True, blFri:=True)
Public Function Dte_Days_Count_To_Today(dDteInp As Date, _
Optional blSun As Boolean, Optional blMon As Boolean, _
Optional blTue As Boolean, Optional blWed As Boolean, _
Optional blThu As Boolean, Optional blFri As Boolean, _
Optional blSat As Boolean)
Dim aDaysT As Variant, bDayT As Byte 'Days Target
Dim bDayI As Byte 'Day Ini
Dim iWeeks As Integer 'Weeks Period
Dim bDaysR As Byte 'Days Remaining
Dim bDaysA As Byte 'Days Additional
Dim aDaysC(7) As Integer 'Days count
Rem Set Days Base
aDaysT = Array(blSun, blMon, blTue, blWed, blThu, blFri, blSat)
bDayI = Weekday(dDteInp, vbSunday)
iWeeks = Int((Date - dDteInp + 1)/7)
bDaysR = (Date - dDteInp + 1) Mod 7
Rem Set Day Target Count
For bDayT = 1 To 7
bDaysA = 0
aDaysC(bDayT) = 0
If aDaysT(bDayT) Then
If bDaysR = 0 Then
bDaysA = 0
ElseIf bDayI = bDayT Then
bDaysA = 1
ElseIf bDayI < bDayT Then
If bDayI + bDaysR - 1 >= bDayT Then bDaysA = 1
Else
If bDayI + bDaysR - 8 >= bDayT Then bDaysA = 1
End If
Rem Target Day Total
aDaysC(bDayT) = iWeeks + bDaysA
End If: Next
Rem Set Results - Total Days
Dte_Days_Count_To_Today = WorksheetFunction.Sum(aDaysC)
End Function
推薦閱讀以下網頁獲得的資源有了更深的瞭解叫它使用:
Option keyword, Variables & Constants, Data Type Summary,
Optional keyword, Function Statement, For...Next Statement,
If...Then...Else Statement, Control and Dialog Box Events,
Select Case Statement, WorksheetFunction Object (Excel)
任何解釋的downvote?這對我來說非常合適。 – Alex4336
我得到了一個編譯錯誤的未定義「HowManyDays」 – GregNH
你是否從我的答案的頂部實現了功能? – Alex4336