Excel VBA:For 循环计算除最后一行以外的所有内容。第一行的文本 header 需要遗漏

Excel VBA: For Loop calculates everything but last row. Text header in first row needs missed

我设法解决了一个问题,即我 VBA 忽略 sheet 的 header 行并对剩余数据执行计算。下面的代码。但是现在我已经开始工作了,它错过了最后一行,无论我正在处理多少行数据。数据中没有理由这样做 - 最后一行有值,并且值的类型与代码工作的行相同。

E 列是唯一在所有单元格中都有数据的列。当我使用 "For i = 1 to ..." 时收到 Run-time 错误 13,当我将其更改为 "For i = 2 to ..." 时代码有效。

Option Explicit

Sub CalcTotalLTA()

Dim i As Variant
Dim ws As Worksheet
Set ws = Worksheets("Input")

'counts the no. of rows in E and loops through all
For i = 2 To ws.Range("E2", ws.Range("E2").End(xlDown)).Rows.Count

'Identifies rows where columns BU has a value
If ws.Cells(i, 73).Value <> "" Then

'calculate Total LTA

ws.Cells(i, 76).NumberFormat = "0.00"
ws.Cells(i, 76).Value = ws.Cells(i, 73).Value * 20

End If

Next i

End Sub

For i = 2 To ws.Range("E2", ws.Range("E2").End(xlDown)).Rows.Count 更改为 For i = 2 To ws.Range("E2", ws.Range("E2").End(xlDown)).Rows.Count + 1

假设您有 10 行数据,位于第 2-11 行。你的代码说 "From rows 2 to 10, do this logic." 但你想在第 2-11 行做。

试试这个:

Sub CalcTotalLTA()

Dim i As Variant
Dim ws As Worksheet
Dim lngLRow As Long

    Set ws = Worksheets("Input")

    With ws
        lngLRow = .Cells(Rows.Count, "E").End(xlUp).Row
        'counts the no. of rows in E and loops through all
        For i = 2 To lngLRow
        'Identifies rows where columns BU has a value
            If .Cells(i, 73).Value <> "" Then
                'calculate Total LTA
                .Cells(i, 76).NumberFormat = "0.00"
                .Cells(i, 76).Value = .Cells(i, 73).Value * 20
            End If
        Next i
    End With

End Sub