带有日期的Excel VBA脚本循环

时间:2013-02-22 04:16:45

标签: vba date

我正在计算2个指定日期之间的工作时数(上午8点到晚上8点),不包括周末和公众假期,但我的代码语法不正确。

示例数据:

开始日期:17/06/2011 08:00:00 AM

结束日:19/06/2011 08:00:00 PM

Sub SLA_Days_Resolved_F()
    Dim x As Integer
    ' Set numrows = number of rows of data.
    NumRows = Range("F2", Range("F2").End(xlDown)).Rows.Count

    Dim total As Integer 'to count the total hours
    Dim st As String 'start date cell
    Dim en As String 'end date cell
    Dim destCell As String
    Dim d As Date ' for the loop

    total = 0

    ' Establish "For" loop to loop "numrows" number of times.
    For x = 2 To NumRows + 1
        st = "G" & CStr(x) 'reference to the cells
        en = "D" & CStr(x)
        'loop from start date to end date
        For d = Date(Range(st)) To Date(Range(en))
            'check if the current date is found is a Public holiday in the range or if a weekend
            If ((Vlookup(d,lookups!$o$3:$p$26,2,false))=1) or (weekend(d))Then
                'minus 8 to remove hours before 8am.
                total = (total + Hour(d) + minutes(d) / 60) - 8
            End If
        Next
    Next
End Sub

1 个答案:

答案 0 :(得分:9)

您没有为变量sten分配任何值。

Date不是VBA中可用的功能。您可能需要使用DateSerial函数。这是一个循环日期的简单示例,您应该能够修改它。

Sub LoopDates()
Dim d As Date
'Loop the days beteween today and March 1, 2013.
For d = DateSerial(Year(Now), Month(Now), Day(Now)) To DateSerial(2013, 3, 1)

    Debug.Print d  'Prints the "d" value in the immediate window.
Next

End Sub

此外,您不能只将工作表公式放在VBA中。这行肯定是Vlookup的错误语法,Weekend不是我所知道的公式(测试似乎证实它不是工作表或VBA中的有效调用。

If ((Vlookup(d,lookups!$o$3:$p$26,2,false))=1) or (weekend(d))Then

重写为:

If Application.WorksheetFunction.Vlookup(d,Sheets("lookups").Range("$o$3:$p$26"),2,false)=1 _
    or Not Application.WorksheetFunction.Weekday(d) Then

日期循环的另一个例子,我已经根据我认为更有效的方式对变量进行了标注:

Sub Test()

Dim st As Range
Dim x As Integer
Dim stDate As Date
Dim enDate As Date
Dim d As Date
Dim numRows as Long

NumRows = Range("F2", Range("F2").End(xlDown)).Rows.Count

For x = 0 To NumRows-2
'SET YOUR VARIABLES HERE
' This may seem redundant or unnecessary for this case, but it makes structuring nested
' loops easier to work with, and then there are fewer places to make changes, 
' if you need to make changes.

    Set st = Range("G2").Offset(x, 0)
    Set en = Range("D2").Offset(x, 0)
    stDate = DateSerial(Year(st), Month(st), Day(st))
    enDate = DateSerial(Year(en), Month(en), Day(en))

    'Then, loop through the dates as necessary
    For d = stDate To enDate
        Debug.Print d
        'Do your code here.
    Next

Next


End Sub