VBA计算整行的总工作日

时间:2015-11-02 05:06:36

标签: vba excel-vba loops excel

我想从一段时间内计算工作日的总和(周六和周日)。循环是可以的,但它没有给出我想要的结果。例如,AD6 = 26/1/2015 5:00:00 PM和T6 = 13/1/2015 8:05:00 AM应该给出4天,但它给出了奇怪的数字807878.

这是什么意思?如何调整我的编码以获得我想要的?我用这个过程的代码。 谢谢!

Sub CalcWeek()
Dim Date1 As Date, Date2 As Date, dateToCheck As Date
Dim daysBetween As Long, weekdays As Long, i As Long

Dim lrow As Long
Dim PRow As Long
Dim CurrentSheet As Worksheet
Set CurrentSheet = Excel.ActiveSheet
FRow = CurrentSheet.UsedRange.Cells(1).Row
lrow = CurrentSheet.UsedRange.Rows(CurrentSheet.UsedRange.Rows.count).Row

weekdays = 0

For PRow = lrow To 2 Step -1

For i = 0 To DateDiff("d", (CurrentSheet.Cells(PRow, "AD").Value), (CurrentSheet.Cells(PRow, "T").Value))

dateToCheck = DateAdd("d", i, CurrentSheet.Cells(PRow, "AD").Value)

If (Weekday(dateToCheck) <> 2 And Weekday(dateToCheck) <> 3 And Weekday(dateToCheck) <> 4 And Weekday(dateToCheck) <> 5 And Weekday(dateToCheck) <> 6) Then
CurrentSheet.Cells(PRow, "AI").Value = CurrentSheet.Cells(PRow, "AI").Value + 1
End If

Next i
'CurrentSheet.Cells(PRow, "AJ").Value = weekdays
Next PRow
End Sub

1 个答案:

答案 0 :(得分:0)

最后我得到了我需要的东西!

Sub WeekDaysTotally()

Dim Date1 As Date, Date2 As Date, dateToCheck As Date
Dim daysBetween As Long, weekdays As Long, i As Long

Dim lrow As Long
Dim PRow As Long
Dim CurrentSheet As Worksheet
Set CurrentSheet = Excel.ActiveSheet
FRow = CurrentSheet.UsedRange.Cells(1).Row
lrow = CurrentSheet.UsedRange.Rows(CurrentSheet.UsedRange.Rows.count).Row

For PRow = lrow To 2 Step -1
weekdays = 0

Date1 = Cells(PRow, "T")
Date2 = Cells(PRow, "AD")
daysBetween = DateDiff("d", Date1, Date2)

For i = 0 To daysBetween

 dateToCheck = DateAdd("d", i, Date1)
 If Cells(PRow, "U").Value <> "" And Cells(PRow, "S").Value <> "" Then
 If (Weekday(dateToCheck) <> 2 And Weekday(dateToCheck) <> 3 And Weekday(dateToCheck) <> 4 And Weekday(dateToCheck) <> 5 And Weekday(dateToCheck) <> 6) Then
    weekdays = weekdays + 1
 End If
 End If
Next i

Cells(PRow, "AL") = weekdays

Next PRow
End Sub

此子计算器将仅计算整个单元格的工作日总数。 &GT;&LT;