在选择旁边的新列中汇总列

问题描述 投票:0回答:3

我试图在一个新专栏中总结一些列。

我已经能够达到A + B并将值放在C中的点。但是,我需要求和的实际列有所不同。有没有办法可以编辑我的代码,以便任何选定的列可以在选择右侧的新列中求和?

例如。如果我选择BD列,它会在E中插入一个新列,其中包含列B,C和D的总和。或者,如果我选择了EF,它将在G中插入一个新列,其中包含列E和F的总和。

Sub SumColumns()

Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).row

For i = 1 To Lastrow
    Range("C" & i).Value = Range("A" & i).Value + Range("B" & i).Value
Next i

End Sub
excel vba excel-vba excel-formula
3个回答
0
投票

这是我(相当邋)的解决方案:

Sub Test()

Dim col1 As String, col2 As String, lastrow As Long

col1 = Split(Selection.Address, "$")(1)
col2 = Split(Selection.Address, "$")(3)

lastrow = Cells(Rows.Count, col2).End(xlUp).Row

Columns(col2 & ":" & col2).Offset(0, 1).Insert Shift:=xlToRight

For i = 1 To lastrow
    Range(col2 & i).Offset(0, 1).Value = WorksheetFunction.Sum(Range(col1 & i & ":" & col2 & i))
Next i

End Sub

我说这很草率,因为如果你选择了整个列,你就不会恰当地Split列出值。所以这取决于你是如何尝试这样做的。

img1


0
投票

此过程将允许您选择任何范围。它将在范围的末尾添加一列,并将每一行与新列相加。

Sub test()
    Call InsertSumCol(Sheet1.Range("B2:E4"))
    Call InsertSumCol(Sheet2.Range("E1:F3"))
End Sub

Private Sub InsertSumCol(ByVal oRange As Range)

    'Add Sum Column to end of Range
    oRange.Worksheet.Columns(oRange.Column + oRange.Columns.Count).Insert shift:=xlToRight

    ' Sum Each Row in Range
    Dim oRow As Range
    For Each oRow In oRange.Rows
        oRow.Cells(1, oRow.Columns.Count + 1) = WorksheetFunction.Sum(oRow)
    Next

End Sub

0
投票

我假设你想要从A列开始垂直求和一行中的所有单元格。

试试这个(代码中有一些提示和注释):

'use this in order to avoid errors
Option Explicit

Sub SumColumns()
    'always declare variables!
    Dim LastRow As Long, i As Long, ws As Worksheet, lastCol As Long, firstCol As Long
    'if you can, avoid using ActiveSheet, Selection, etc. it's prone to errors
    Set ws = ActiveSheet
    i = 1
    Do
        firstCol = ws.Cells(i, 1).End(xlToRight).Column
        lastCol = ws.Cells(i, ws.Columns.Count).End(xlToLeft).Column
        'there isn't any filled cells in a row
        If lastCol = 1 Then Exit Do

        ws.Cells(i, lastCol + 1).Value = Application.WorksheetFunction.Sum(ws.Range(ws.Cells(i, firstCol), ws.Cells(i, lastCol)))

        i = i + 1
    Loop While True

End Sub

之前和之后:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.