VBA Excel Sum列和行

时间:2014-10-15 15:25:00

标签: sql excel vba excel-vba

    ABC ASD BHP WER THY SUM    
1   789 564 654 546 654 3207

2   103 123 213 123 654 1216    
3   546 394 879 654 654 2733

我的问题是如何对每列和每行求和?如果有一个缺口行?我试图处理每一行,以便它总和。如果数据中没有间隙,它可以工作,但如果行之间存在间隙,则不能完全处理每个单元格。

这就是我所拥有的:

Sub test()

Dim intRowTot As Integer
Dim intRowCnt As Integer
Dim intColTot As Integer
Dim intColCnt As Integer

Range("B2").Select
Do Until IsEmpty(ActiveCell)

    intRowTot = 0
    intColTot = 0

    Do Until IsEmpty(ActiveCell)
        intRowTot = intRowTot + 1
        intColTot = intColTot + ActiveCell.Value
        intColCnt = intColCnt + 1
        ActiveCell.Offset(1, 0).Select

    Loop
    ActiveCell.Offset(1, 0).Value = intColTot
    ActiveCell.Offset(-intRowTot, 1).Select
    Loop

Range("B2").Select
Do Until IsEmpty(ActiveCell)

    intRowTot = 0
    intColTot = 0

    Do Until IsEmpty(ActiveCell)
        intRowTot = intRowTot + ActiveCell.Value
        intColTot = intColTot + 1
        intRowCnt = intRowCnt + 1
        ActiveCell.Offset(0, 1).Select
    Loop

    ActiveCell.Offset(0, 1).Value = intRowTot
    ActiveCell.Offset(1, -intColTot).Select
    Loop
End Sub`

2 个答案:

答案 0 :(得分:0)

您最好的选择几乎是100%不使用VBA,而是使用电子表格公式:

=SUM(B2:B4)

如果您出于某种原因100%需要使用VBA,电子表格公式仍然可能是正确的答案:

Application.WorksheetFunction.Sum(Range("B2:B4"))

答案 1 :(得分:0)

ABC ASD BHP WER THY    
789 564 654 546 654

103 123 213 123 654   
546 394 879 654 654

上表,代码如下:

Sub test()


Dim i As Integer
Dim j As Integer
Dim tempsum As Long
'columns
For i = 1 To 5
    tempsum = 0
    For j = 1 To 5
        If IsNumeric(Cells(j, i).Value) = True Then
            tempsum = tempsum + Cells(j, i).Value
        End If
    Next
    If tempsum > 0 Then
        Cells(j, i).Value = tempsum
    End If
Next


'rows
For i = 1 To 5
    tempsum = 0
    For j = 1 To 5
        If IsNumeric(Cells(i, j).Value) = True Then
            tempsum = tempsum + Cells(i, j).Value
        End If
    Next
    If tempsum > 0 Then
        Cells(i, j).Value = tempsum
    End If
Next



End Sub