我正在尝试使用多个列执行计算并将值分配给列

时间:2017-08-02 19:56:33

标签: vba excel-vba excel

我正在尝试根据其他列的计算为列分配值。我希望它遍历所有行并执行相同的计算。但没有任何反应。

Sub calculateIncome()
  Dim i As Integer
  i = 2

  Dim counter As Integer
  counter = 2

  Dim j As Integer
  For j = 2 To i
    Worksheets("owssvr").Range("af" & j).Value = _
      Worksheets("owssvr").Range("v" & j).Value + Worksheets("owssvr").Range("y" & _
      j).Value + Worksheets("owssvr").Range("ab" & j).Value
    j= j + 1
  Next j

End Sub

1 个答案:

答案 0 :(得分:1)

您需要这样做:

Sub calculateIncome()
    Dim startLine As Integer
    Dim endLine As Integer
    Dim currentLine As Integer
    Dim ws As Worksheet
    startLine = 2 ' you must preset
    endLine = 126 ' you must preset
    Set ws = Worksheets("owssvr")
    For currentLine = startLine To endLine
        ws.Range("af" & currentLine).Value = _
            ws.Range("v" & currentLine).Value + _
            ws.Range("y" & currentLine).Value + _
            ws.Range("ab" & currentLine).Value
    Next
End Sub

但是,嗯,为什么不在单元格=V2+Y2+AB2中输入AF2,然后将公式一直复制到列表中?