如何遍历一列,从第二列添加值?

时间:2019-06-12 13:25:30

标签: excel vba

我在表中有两列,假设a和b。实现宏后,a中的单元格值将为a = a + b。执行加法后,b列中的所有值都将设置为0。

我尝试使用for循环遍历列中的每个单元格并添加值,但是什么也没有发生。

max.poll.interval.ms

没有错误消息发生,但在我测试时实际上什么也没有发生。

5 个答案:

答案 0 :(得分:3)

确保始终将Option Explicit写在模块顶部。因此,它将确保声明代码中的所有变量。在上面的代码中,它没有进入循环,因为未声明NumRows,因此其值为0。尝试以下方法:

Option Explicit

Sub TestMe()

    Dim i As Long
    For i = 2 To 10
        With Worksheets(1)
            .Cells(i, 4).Value = WorksheetFunction.Sum(.Cells(i, 4).Value, .Cells(i, 5).Value)
        End With
    Next i

End Sub

答案 1 :(得分:1)

尝试:

Option Explicit

Sub zeroAndAdd0_Click()

    Dim NumRows As Long

    'Change Sheet name
    With ThisWorkbook.Worksheets("Sheet1")

        'NumRows take tha value of a fix number
        NumRows = 10
        'NumRows take the value of Column D last row
        NumRows = .Cells(.Rows.Count, "D").End(xlUp).Row

        .Range(.Cells(2, 4), .Cells(NumRows, 4)).Formula = "=Sum(D2,E2)"

    End With

End Sub

答案 2 :(得分:0)

如果代码完全符合您的问题,我认为不会填充NumRows

尝试

Sub zeroAndAdd0_Click()
Dim i As Long, NumRows As Long, csum As Double
Dim c As Range

With Workbooks(REF).Sheets(REF)
    NumRows = .Cells(.Rows.Count, "D").End(xlUp).Row 'last row in Col D
    'For each is faster than For i when looping through a range
    For Each c In Range("D2:D" & NumRows) 
        csum = c.Value + c.Offset(,1).Value 'Populate a variable with the sum of the two cells
        c.Value = csum 'Populate the cell in col D with the sum
        c.Offset(,1).Value = 0 'Set the other cell to 0
    Next c
End With

End Sub

注释掉的代码中的信息

答案 3 :(得分:0)

这将起作用:

Sub zeroAndAdd0_Click()

    For i = 2 To Cells(Rows.Count, 4).End(xlUp).Row

        Cells(i, 4).Value = Cells(i, 4).Value + Cells(i, 5).Value
        Cells(i, 5).Value = 0

    Next i

End Sub

它将为您完成两项工作。无需使用Worksheet Function

答案 4 :(得分:0)

您只需要定义您的NumRows变量(即NumRows = Sheet1.Range(“ D”&Rows.Count).End(xlUp).Row),然后完成将E列中的值转换为0。像这样:

Sub zeroAndAdd0_Click()

    Dim NumRows, i As Long
    NumRows = Sheet1.Range("D" & Rows.Count).End(xlUp).Row

    For i = 2 To NumRows
        Cells(i, 4).Value = WorksheetFunction.Sum(Cells(i, 4).Value, Cells(i, 5).Value)
        Cells(i, 5).Value = 0
    Next i

End Sub