首页 > 解决方案 > 计算耗时超过预期的任务实例数

问题描述

我在 Excel VBA 中有一个宏,其中包含一组任务的输入,以及每个任务花费的时间。每个任务有多个实例。

我想计算每个任务有多少实例过期。逾期的时间取决于任务,所以我添加了一个输入框,以便用户可以为每个任务输入。然后,宏应该检查每个任务有多少实例比这个输入花费的时间更长。

例如,如果任务 1 有 3 个实例,分别用时 2 天、3 天和 4 天,我输入预期时间为 2 天,这应该返回 2 个任务实例已过期。

我的代码输出的数字在手动检查时是错误的 - 通常远低于实际值。

我已经尝试确保所有内容都是整数,以防出现问题,但它没有改变任何东西。

Sub Macro1()
Dim AshRow As Integer
Dim EweRow As Integer
Dim lastCell As Long
Dim all As Range
Dim allRows As Range
Dim count As Integer
Dim origTasks As Range
'Previously tried Dim expTime As Variant
Dim expTime As Integer
Dim m As Integer
Dim task As String

EweRow = Sheets("Sheet1").UsedRange.Rows.count

With Sheets("Sheet1")
    lastCell = Cells(Rows.count, "A").End(xlUp).Row
    Set all = Range("A1", Range("A" & lastCell))
End With

    Set origTasks = Worksheets("Page1_1").Range("A2", "A" & EweRow)

    'For each task, cycle through each row of the original report and note anything over the given value

    Set allRows = Range("A2", Range("A" & lastCell))

    For Each r In allRows.Cells
        count = 0
        task = r.Value
        expTime = InputBox("Please enter the expected time for the task: " & task)
        'Check this is an integer and make it one if not
        If Not IsNumeric(expTime) Then
            expTime = CInt(expTime)
        End If

        For Each n In origTasks.Cells
            If n.Value = task Then
                m = n.Offset(0, 1).Value
                'Check value is an integer
                If Not IsNumeric(m) Then
                    m = CInt(m)
                End If

                If m > expTime Then
                    count = count + 1
                End If
            End If
        Next n
    r.Offset(0, 4).Value = count  
    Next r

    'Format
    Worksheets("Sheet1").Range("A1:E1").Font.Bold = True

End Sub

标签: excelvba

解决方案


推荐阅读