如何创建可以将未知数字列和固定行数相加的代码?

时间:2017-05-17 09:40:19

标签: excel vba

我正在尝试编写能够在电子表格中添加任意数量的列的代码。我很清楚这可以是硬编码的,但是我正在尝试编写可以使用任意数量的列的代码,而无需每次都更改代码。

这就是我要输出的内容(总计列在每列的底部):

  A   |   B                                        A   |   B   |   C
----- | -----                                    ----- | ----- | -----
  20  |   30                                       20  |   30  |    4
----- | -----                                    ----- | ----- | -----
   3  |   45      Now another column is added:      3  |   45  |   55    
----- | -----                                    ----- | ----- | -----
  13  |    4                                       13  |    4  |   15
-------------                                    ---------------------
  36  |   79                                       36  |   79  |   74

这是我目前的代码:

Sub Button1_Click()
    Range("b1").Select
    ActiveCell.End(xlDown).Select
    Range("b1").Select
    ActiveCell.End(xlDown).Select
    Dim vStartRow As Integer
    vStartRow = 2
    Dim vEndRow As Integer
    vEndRow = ActiveCell.Row
    Dim vStartColumn As Integer
    vStartColumn = 2
    Dim vEndColumn As Integer
    vEndColumn = ActiveCell.Column
    Cells(vEndRow + 1, vEndColumn).Formula = "=sum(b" & vStartRow & ":b" & vEndRow & ")"
    Cells(vEndRow, vEndColumn + 1).Select
End Sub

注意:我希望在点击按钮而不是一次性完成所有计算时

2 个答案:

答案 0 :(得分:1)

使用VirtualAlloc((uint_t*)ptr+offset, ..., MEM_COMMIT, ...);这样的表示法。

VirtualFree(ptr, 0, MEM_RELEASE)

应位于R1C1,然后分配到With Sheet1 '/* Change with your actual sheet code name */ Dim lc As Long, fr As Long Dim r As Range, c As Range fr = 3 '/* change it to your actual static row lc = .Cells(fr, .Columns.Count).End(xlToLeft).Column Set r = .Range("A1", .Cells(3, lc)) For Each c In r.Offset(fr).Resize(1) If Not c.HasFormula Then c.FormulaR1C1 = "=SUM(R[-" & fr & "]C:R[-1]C)" Exit For End If Next End With

答案 1 :(得分:0)

以下是我为上面示例中要查找的输出创建的函数。此代码将添加任意数量的列,并将为您提供第5行中的总计。您可以在按钮上实现此功能。

Sub AddColumns()

Dim ColumnCount As Integer
Dim Rownumber As Integer
Dim ColumnNumber As Integer
Dim TotalValue As Integer

ColumnCount = ActiveSheet.UsedRange.Columns.Count
For ColumnNumber = 1 To ColumnCount
TotalValue = 0
    For Rownumber = 2 To 4
        TotalValue = TotalValue + Cells(Rownumber, ColumnNumber)
    Next Rownumber
    Cells(5, ColumnNumber) = TotalValue
Next ColumnNumber

End Sub