4行后如何继续计数?

时间:2019-06-12 21:30:03

标签: excel vba

向我提供了一些不再有空的家伙提供的代码。说您有一个包含五列的表格。前四列填充有运行良好的查询,然后有一段代码完成了第五列。当我运行它时,它进入第五行及以下行时,我得到“下标超出范围(错误9)”的信息。 1,2,3和4正常。任何帮助将是巨大的!错误在fisrt“ for”上方的行上突出显示

    Function HorasSemana() As Double
        Dim sumaHoras As Double
        Dim lRow As Integer
        Dim semanas(1 To 4) As Integer

        lRow = DatosOmnia.Cells(Rows.Count, 1).End(xlUp).Row

        For i = 2 To lRow
            semanas(i - 1) = WorksheetFunction.WeekNum(DatosOmnia.Cells(i, "C"), vbMonday)
            'MsgBox WorksheetFunction.WeekNum(DatosOmnia.Cells(i, "C"), vbMonday)
        Next i

        'lRow toma el valor con respecto a la hoja "Horas Semanales"
        lRow = Worksheets("Horas Semanales").Cells(Rows.Count, 1).End(xlUp).Row
        For i = 1 To sizeOf(semanas) '(UBound(semanas, 1) - LBound(semanas, 1) + 1)
            sumaHoras = 0
            For j = 2 To lRow
                If WorksheetFunction.WeekNum(Worksheets("Horas Semanales").Cells(j, "B"), vbMonday) = semanas(i) Then
                    sumaHoras = sumaHoras + Worksheets("Horas Semanales").Cells(j, "C").Value
                    DatosOmnia.Cells(i + 1, "F") = sumaHoras
                End If
            Next j
        Next i
        HorasSemana = sumaHoras
End Function

1 个答案:

答案 0 :(得分:0)

您可以根据lRow调整数组大小:

    Dim lRow As Long
    Dim semanas() As Long

    lRow = DatosOmnia.Cells(Rows.Count, 1).End(xlUp).Row
    ReDim semanas(1 to lRow-1)

Long通常比Integer更可取-它不会“花费”更多,并且如果您的数据变大则更安全