应用程序或用户定义的错误

时间:2017-05-31 20:51:14

标签: excel excel-vba dictionary vba

我的一本工作簿中有以下代码。基本上,有两个表 - 一个带有矩阵,其中顶行是名称,左列是日期。截至目前,“出勤”电子表格中有735行(或日期),以及大约80个个人名称。它应该跟踪人们的出席情况。

我需要了解每个人每周的工作量。以下代码尝试执行以下操作:

  1. 对于每个人,扫描第一个7天(或7行)的时间段。总结那段时间,并将值放在字典中的增量项目中。因此,例如,在700天内,将有一个100单位的字典。仅当要添加到字典中的值大于0(如果它们在那一周工作)时才执行此操作。
  2. 拿这本字典,总结字典中所有项目的值,然后除以该字典的计数,以获得7天块内的平均工作周。
  3. 然后,将该词典的值放入另一个词典中,其中个人姓名(考勤表中的顶行)是键,前一个词典的值是该项目。
  4. 在“摘要表”中,将与每个键关联的项目放在第9列中。例如 -
  5. 个人|每周工作时间
    约翰| 20个
    简| 15个
    乔| 12

    希望能够直接从输入电子表格的出勤数据中得出每个人每周单位(而不是7个单位块)的工作量。

    错误发生在以下行:

     For k = 2 To attendanceSheet.Range("a1").End(xlRight).Row
    

    Excel表示“应用程序或用户定义的错误:#1004”

    此外,任何有关优化的帮助都会受到赞赏,因为这似乎是相当庞大的代码。

      Public Sub calculateAverageWeek()
    
        Dim i As Long
    
        Dim attendanceSheet As Worksheet
        Set attendanceSheet = ActiveWorkbook.Worksheets("Attendance")
    
        'calculate week block
        Dim lastRow As Long
        lastRow = attendanceSheet.Range("a1").End(xlDown).Row
    
        Dim indivName As Dictionary
        Set indivName = New Dictionary
    
        Dim k As Long
        For k = 2 To attendanceSheet.Range("a1").End(xlRight).Row
                Dim total As Long
                Dim v As Variant
                Dim totalWeeklyHours As Dictionary
                Set totalWeeklyHours = New Dictionary
                Dim j As Long
                j = 1
                Dim curTotal As Double
                curTotal = 0
    
            'scan attendance worksheet
            For i = 2 To lastRow
    
                curTotal = curTotal + attendanceSheet.Cells(i, 2)
                If (i - 1) Mod 7 = 0 Then
                    If curTotal > 0 Then
                        totalWeeklyHours.Add j, curTotal
                        j = j + 1
                        curTotal = 0
                    Else
                    End If
                End If
    
                If i = lastRow Then
                    For Each v In totalWeeklyHours
                        total = total + totalWeeklyHours.Item(v)
                    Next
                   ' Worksheets("Summary").Cells(2, 9) = CLng(total / totalWeeklyHours.Count)
                   indivName.Add attendanceSheet.Cells(k, 1), attendanceSheet.Cells(k, CLng(total / totalWeeklyHours.Count))
                End If
            Next i
        Next k
    
        For i = 2 To Worksheets("Summary").Range("A2").End(xlDown).Row
            Worksheets("Summary").Cells(i, 9) = indivName.Item(Cells(i, 1))
    
        Next i
    
    
    
    End Sub
    

0 个答案:

没有答案
相关问题