代码之家  ›  专栏  ›  技术社区  ›  CodeyMcCode

Excel VBA:For循环计算除最后一行之外的所有内容。缺少第一行的文本标题

  •  -1
  • CodeyMcCode  · 技术社区  · 8 年前

    我已经设法解决了一个问题,即我让VBA忽略我的工作表的标题行,并对剩余的数据执行计算。代码如下。然而,现在我有了它,不管我处理多少行数据,它都会错过最后一行。数据中没有理由这样做-最后一行有值,并且值的类型与代码工作的行相同。

    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
    
    2 回复  |  直到 8 年前
        1
  •  0
  •   Daniel    8 年前

    改变 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

        2
  •  0
  •   maaajo    8 年前

    试试这个:

    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