Application.WorksheetFunction.Sum在循环中

时间:2012-01-19 15:31:49

标签: excel vba excel-vba

我有这个代码从sql查询中检索一些数据并将它放在Excel工作表中:

   I = 4
 Do While Not rs.EOF
  I = I + 1
  Sheet1.Range("A" & I).Value = rs(0)
  Sheet1.Range("B" & I).Value = rs(1)
  Sheet1.Range("C" & I).Value = rs(2)
  Sheet1.Range("D" & I).Value = rs(3)
  Sheet1.Range("E" & I).Value = rs(4)
  Sheet1.Range("F" & I).Value = rs(5)
  Sheet1.Range("G" & I).Value = rs(6)
  Sheet1.Range("H" & I).Value = rs(7)
  Sheet1.Range("I" & I).Value = rs(8)
  Sheet1.Range("J" & I).Value = rs(9)
  Sheet1.Range("K" & I).Value = rs(10)
  Sheet1.Range("L" & I).Value = rs(11)
  Sheet1.Range("M" & I).Value = rs(12)
  Sheet1.Range("N" & I).Value = rs(13)
  Sheet1.Range("O" & I).Value = rs(14)
  Sheet1.Range("P" & I).Value = rs(15)
  Sheet1.Range("Q" & I).Value = Application.WorksheetFunction.Sum(Sheet1.Range("E" & I), Sheet1.Range("P" & I))
  'Sheet1.Range("Q" & I).Value = Sheet1.Range("E" & I).Value + Sheet1.Range("F" & I).Value + Sheet1.Range("G" & I).Value + Sheet1.Range("H" & I).Value
  rs.MoveNext
 Loop

现在,我正在尝试将一系列列从col“E”加到col“P”,但它不起作用,它只是对那些单元格求和(“E”和“I”和“P”& ; I),而不是范围。

请帮忙吗?

2 个答案:

答案 0 :(得分:6)

首先,您可以使用with语句优化和清理代码:

使用with

清理您的代码

不要

Sheet1.Range("A" & I).Value = rs(0)
Sheet1.Range("B" & I).Value = rs(1)
Sheet1.Range("C" & I).Value = rs(2)
...

<强>不要

With Sheet1
    .Range("A" & I).Value = rs(0)
    .Range("B" & I).Value = rs(1)
    .Range("C" & I).Value = rs(2)
    ...
End With

求和范围而不是单元格

了解您的原始陈述

在您的原始陈述中:

Application.WorksheetFunction.Sum(Sheet1.Range("E" & I), Sheet1.Range("P" & I))

您正在使用多个参数调用工作表函数(就像使用SUM(E1, P1)一样,但您想要对范围求和,即SUM(E1:P1)

解决您的问题

更好的尝试:

Application.WorksheetFunction.Sum(Sheet1.Range("E" & I & ":P" & I))

请注意,您也可以通过以下方式定义范围:

With Sheet1
    Application.WorksheetFunction.Sum(.Range(.Cells(I, "E"), .Cells(I, "P"))
End With

后者非常有用,因为您可以将.Cells与字母或Long一起用于列。

答案 1 :(得分:3)

为什么不使用循环代替这么长的代码

Option Explicit

Sub Sample()
    Dim i As Long, j As Long, k As Long

    '~~> Rest of your code

    Do While Not rs.EOF
        i = i + 1
        j = 0
        With Sheets1
            k = 1
            For j = 0 To 15
                .Cells(i, k).Value = rs(j)
                k = k + 1
            Next
            .Range("Q" & i).Value = _
            Application.WorksheetFunction.Sum(.Range("E" & i & ":P" & i))
        End With
        rs.MoveNext
     Loop

     '~~> Rest of your code
End Sub