这是我在 Excel 中遇到错误的代码:
Sub Start_EndDelayInMonth()
With Sheets("Analysis Worksheet")
Dim i As Long
Dim LastRow As Long
LastRow = Range("N" & Rows.Count).End(xlUp).Row
'This is where the error occurs.
If Sheets("Analysis Worksheet").Cells(i, 2).Value = 1 And Sheets("Analysis Worksheet").Cells(i, 3).Value = 1 Then
Call CopyCells
End If
If Sheets("Analysis Worksheet").Range("B" & i).Value = 1 And Sheets("Analysis Worksheet").Range("C" & i).Value = 2 Then
Call CopyCells
End If
If Sheets("Analysis Worksheet").Range("B" & i).Value = 1 And Sheets("Analysis Worksheet").Range("C" & i).Value = 3 Then
Call CopyCells
End If
'--Then the code continues on in the same fashion, ending with:
End With
End Sub
有人能帮我理解为什么会出现运行时错误吗?谢谢!
CopyCells 代码是:
Sub CopyCells()
Dim i As Long
Dim j As Long
Dim k As Long
Dim LastRow As Long
LastRow = Range("N" & Rows.Count).End(xlUp).Row
j = 26
k = 2
For i = 5 To LastRow
Sheets("Analysis Worksheet").Cells(i, j).Value = Sheets("Analysis Worksheet").Cells(i, (j - k)).Value
Sheets("Analysis Worksheet").Cells(i, (j - k)).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 1))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 1))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 2))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 2))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 3))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 3))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 4))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 4))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 5))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 5))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 6))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 6))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 7))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 7))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 8))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 8))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 9))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 9))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 10))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 10))).Value = Sheets("Analysis Worksheet").Cells(i, (j - (k + 11))).Value
Sheets("Analysis Worksheet").Cells(i, (j - (k + 11))).Value = 0
j = j + 1
k = k + 1
Next i
If k < (k + 1) Then
Sheets("Analysis Worksheet").Cells(i, (j - (k + 10))).Value = 0
End If
End Sub
答案1
您的代码是
Dim i As Long
Dim LastRow As Long
LastRow = Range("N" & Rows.Count).End(xlUp).Row
'This is where the error occurs.
If Sheets("Analysis Worksheet").Cells(i, 2).Value = 1 And Sheets("Analysis Worksheet").Cells(i, 3).Value = 1 Then
您可以看到,虽然您已经定义了i
但它并未被分配任何值。