If语句上的VBA运行时错误1004

祝大家好日子,我一直执行我的代码时遇到相同的运行时错误。 我没有正式的VBA培训(主要是一些VB在高中)。 代码是这样的

Sub Lavaggi2(): Dim i, j, k, lavaggio, x, daymax As Integer Dim day As Date Dim Ore(10) As Single Dim column_len, row_len As Integer Dim totale_ore As Integer 'Determining variable for row and columns column_len = Sheets("Foglio7").Cells.CurrentRegion.Columns.Count row_len = Sheets("Foglio7").Cells.CurrentRegion.Rows.Count k = 1 For j = 1 To row_len For i = 1 To column_len If (Sheets("Foglio7").Cells(2, i).Value = "Codice") Then If (Sheets("Foglio7").Cells(j, i).Value = "00/100" Or Sheets("Foglio7").Cells(j, i).Value = "00/200") Then day = Sheets("Foglio7").Cells(j, 1).Value For k = 1 To 10 If (Sheets("Foglio7").Cells(j - k, 1).Value = day) Then Ore(k) = Sheets("Foglio7").Cells(j - k, i + 5).Value daymax = daymax + 1 Else End If Next k totale_ore = Worksheet.funcion.Sum(Ore) lavaggio = Sheets("Foglio7").Cells(j, i + 7) / totale_ore For x = 1 To daymax Sheets("Foglio7").Cells(j - x, i + 7).Value = lavaggio * Ore(x) Next x Erase Ore End If End If Next i Next j End Sub 

我得到错误的行是

  If (Sheets("Foglio7").Cells(j - k, 1).Value = day) Then 

我很确定这是一件愚蠢的事情,但是我无法把头围住。

PS:我知道代码可能有点笨拙,但我会在未来的阶段简化它。

感谢所有将回答的人

在循环的第一次迭代中, j - k将等于0,并且您的单元格将为.Cells(0, 1) ,它不存在。

我设法解决了我遇到的问题。 它按预期工作。 感谢所有的帮助

 Sub Lavaggi2(): Dim i, j, k, x, daymax As Integer Dim day As Date Dim lavaggio, totale_ore, Ore(10) As Double Dim column_len, row_len As Integer Application.ScreenUpdating = False Application.Calculation = xlCalculationManual column_len = Sheets("Foglio7").Cells.CurrentRegion.Columns.Count row_len = Sheets("Foglio7").Cells.CurrentRegion.Rows.Count daymax = 1 For j = 1 To row_len For i = 1 To column_len If (Sheets("Foglio7").Cells(2, i).Value = "Codice") Then If (Sheets("Foglio7").Cells(j, i).Value = "00/100" Or Sheets("Foglio7").Cells(j, i).Value = "00/200") Then day = Sheets("Foglio7").Cells(j, 1).Value For k = 1 To 10 If (Sheets("Foglio7").Cells(j - k, 1).Value = day) Then Ore(k) = Sheets("Foglio7").Cells(j - k, i + 5).Value daymax = daymax + 1 Else Exit For End If Next k totale_ore = Application.WorksheetFunction.Sum(Ore) lavaggio = Sheets("Foglio7").Cells(j, i + 7) / totale_ore For x = 1 To daymax - 1 Sheets("Foglio7").Cells(j - x, i + 7).Value = lavaggio * Ore(x) Next x daymax = 1 Erase Ore End If End If Next i Next j Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub 

为了达到最终结果的理想精度,我还调整了声明。