首页 > 解决方案 > 使用变量作为自动求和列 VBA 的列引用

问题描述

我对 VBA 真的很陌生,并且一直在逐段处理一些代码来格式化工作表(我一直在逐段进行,以便我了解每个工作的原理,并使用最终的宏来调用所有的宏都变成一个漫长的过程)。

问题有时是我使用的工作表没有按月按相同顺序导出列(超出我的控制),因此要对特定列进行自动求和,我必须找到列标题,然后自动求和该列,但这使得列字母(或数字)完全可变。我知道如何将行用作变量,但我被困在列上。我一直在搜索论坛试图找到一个简洁的解释,但无济于事。

此代码确实适用于 Y 列,但我试图弄清楚如何让它使用列的变量。例如,我正在使用一个名为“FindInvoiceColumn”的单独宏来选择包含字符串“invoice_amount”的列中的第一个单元格,然后我想使用我在下面编写的内容将“ColumnAddress”设置为列该单元格的值。据我所知.Column 返回列号,这很好,但我假设我必须使用 Cells() 而不是 Range(),我只是不知道如何到达这里。

(部分代码还显示在包含自动总和值的单元格左侧添加单词“Total”,并将两者都设为粗体)。

这是我到目前为止所拥有的:

Dim Rng As Range
   Dim c As Range

   Set Rng = Range("Y" & rows.Count).End(xlUp).Offset(1, 0)
   Set c = Range("Y1").End(xlDown).Offset(1, 0)
   c.Formula = "=SUM(" & Rng.Address(False, False) & ")"

   'Selects next empty row of column X to add "Total" label for sum of column Y'
    Range("X" & Cells.rows.Count).End(xlUp).Offset(1, 0).Select
   ActiveCell.FormulaR1C1 = "Total"

   'Bolds Total and the Sum of invoices'
   Range("X" & Cells.rows.Count).End(xlUp).Select
   Selection.Font.Bold = True
   Range("Y" & Cells.rows.Count).End(xlUp).Select
   Selection.Font.Bold = True```




'The below is what I'd like to use to find the dynamic value of the column.'

'Finds cell in row 1 that contains column header "invoice_amount" and selects it'
 Call FindInvoiceColumn

'Dim ColumnAddress As Integer
 ColumnAddress = ActiveCell.Column

标签: excelvba

解决方案


您可以使用.Address获取列引用,例如:

Sub test()
    Dim varCol As String
    varCol = Columns(ActiveCell.Column).Address
    Debug.Print varCol 'OUTPUTS $A:$A when I had cells(1,1) selected
End Sub

在上面的示例中,我选择了一个单元格来 A) 找到它的列引用,通过.Column和 B) 找到.address所述列的。


.cells()您还可以使用符号而不是符号对定义的范围进行求和.range()

Sub test2()
    Dim rng As Range
    Set rng = Range(Cells(1, 1), Cells(2, 1))
    Cells(3, 1).Formula = "=sum(" & rng.Address & ")"
End Sub

上面的代码输出: 在此处输入图像描述


具体到使用.cells()符号,你可以让你的列引用一个变量,例如:

dim r as long, c as long
r = 1
c = 4
debug.print cells(r,c).address `should output $D$1 (untested)

您可以选择rc满足您的需求。


和往常一样......尽可能避免选择/激活



编辑

通过代码添加对最后一行的使用,因为注释很糟糕:

dim col as long
col = 25 'Y
With sheets("name")
    dim lastRow as long
    lastRow = .cells(.rows.count,col).end(xlup).row
    Dim rng As Range
    Set rng = .Range(.Cells(1, 1), .Cells(lastRow, col))    
end with

这正是我在该部分之后提到关于符号的细节(使用rc作为变量)的原因。


推荐阅读