+ -
当前位置:首页 → 问答吧 → 请老师给看一下如何用VBA求和

请老师给看一下如何用VBA求和

时间:2011-08-05

来源:互联网

请各位老师给看一下这个代码错在那里,如何求和.
Private Sub Worksheet_Change(ByVal Target As Range)
With Sheet1
Application.EnableEvents = False
Dim i As Long
For i = 2 To Range("c65536").End(xlUp).Row
.Cells(i, 5) = .Cells(i, 3) * .Cells(i, 4)
Next i
.Cells(.Range("c65536").End(xlUp).Row + 1, 5) = Application.Sum("e2" & "e" & .Range("e65536").End(xlUp).Row - 1)
.Cells(.Range("C65536").End(xlUp).Row, 2).ClearContents
.Cells(.Range("C65536").End(xlUp).Row + 1, 2) = "合计"
End With
Application.EnableEvents = True
End Sub

附件

如何用VBA求和.rar(9.12 KB)

2011-8-5 21:13, 下载次数: 3

作者: twtthduu   发布时间: 2011-08-05

VBA 中引用工作表函数时,括号中的参数和工作表中使用函数略有不同。另外,对于多次引用的值,比如最后一行的行号,可以定义变量,这样可以简化代码,也可以提供运行速度。
复制内容到剪贴板
代码:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim lRow As Long
    lRow = Range("c65536").End(xlUp).Row
    With Sheet1
        Application.EnableEvents = False
        Dim i As Long
        For i = 2 To lRow
            .Cells(i, 5) = .Cells(i, 3) * .Cells(i, 4)
        Next i
        .Cells(lRow + 1, 5) = Application.Sum(.Range("e2:e" & lRow))
        .Cells(lRow, 2).ClearContents
        .Cells(lRow + 1, 2) = "Total"
    End With
    Application.EnableEvents = True
End Sub

作者: taller   发布时间: 2011-08-05

热门下载

更多