使用宏在Excel中对最后3列求和

时间:2017-06-13 11:19:12

标签: excel vba excel-vba

在Excel文件中,我需要查找最后3列,因为我的列长度每个月都会在新数据到来时更新,并且需要对最后3列值进行求和,因为我想要最近的数据并放入在新专栏中总结。

EG:

A B C D   
1 2 3 4
5 6 7 8
1 2 3 2

在现有工作表中,我想找到B,C,D作为最近的3列(最后3列)并总结并放入新的E列。

A B C D E 
1 2 3 4 9 
5 6 7 8 21 
1 2 3 2 7

请帮我解决使用Excel宏自动化它的方法。在此先感谢您的帮助。我创建了一个代码,但它无法正常工作

Dim LastCol As Integer
With ActiveSheet
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).column
End With
MsgBox LastCol
Dim LastRow As Integer
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "H").End(xlUp).Row
End With
MsgBox LastRow
Dim j As Integer
For i = 2 To LastRow
    For j = LastCol - 2 To LastCol
        Range(i & LastCol + 1).Value = Range(i & j).Value + Range(i & j + 1).Value + Range(i & j + 2).Value
    Next j
Next i

3 个答案:

答案 0 :(得分:1)

将此公式放在E1

=SUM(OFFSET(E1,0,-3,1,3))

获取列E前3列的总和。
每次在E之前插入新列时,它都会自动调整到sum列之前的最后3列。

有关详细信息,请查看OFFSET function

答案 1 :(得分:0)

使用数组,每当您必须处理多个单元格,行或列时。使用数组。首先,您在数组中保存该值,并在内存中使用该数组。 尽量减少与工作簿/工作表/工作表的交互。

它会让您减慢代码的速度,减少错误。

以下是供您参考的代码:

Function getsum()
Dim wb As Workbook
Dim ws As Worksheet
Dim tot_row As Long
Dim row_to_start As Long
Dim cl As Long
Dim irow As Long

Dim sumarr As Variant ' Declare the array

Set wb = ThisWorkbook
Set ws = wb.Sheets(1)

    sumarr = ws.Range("A1").CurrentRegion ' Put the current region in the array
    tot_row = UBound(sumarr, 2) 'Get total rows
    row_to_start = tot_row - 2 ' Get the rows from where sum process with start


    For cl = row_to_start To UBound(sumarr, 2) ' start from 3rd last column till last column
        For irow = LBound(sumarr) + 1 To UBound(sumarr) ' from second row to the last row
            msum = msum + sumarr(irow, cl) ' do the sum
        Next irow
    Next cl
getsum = msum ' return the sum

End Function

答案 2 :(得分:0)


非常感谢你宝贵的时间回复。       我在Excel VBA宏中找到了一个解决方案,它工作得很好!!

 Dim start As Integer
 Dim Mid As Integer
 Dim finish As Integer

 start = LastCol - 2
 Mid = LastCol - 1
 finish = LastCol

 For i = 2 To LastRow
    For j = start To LastCol
      If Not IsEmpty(Range("D" & i).Value) Then
          Cells(i, LastCol + 1).Formula = "=SUM(" & Cells(i, start).Address & ":" & Cells(i, finish).Address & ")"
      End If
   Next j
 Next i