【发布时间】:2020-01-09 03:18:40
【问题描述】:
我真的是 VBA 的新手,并且一直在逐节编写一些代码来格式化工作表(我一直在逐段进行,以便我了解每个代码的工作原理,并使用 final宏将所有宏调用到一个漫长的过程中)。
问题有时是我使用的工作表没有按月以相同的顺序导出列(超出我的控制),因此要对特定列进行自动求和,我必须找到列标题,然后自动求和该列,但这使得列字母(或数字)完全可变。我知道如何将行用作变量,但我被困在列上。我一直在搜索论坛以尝试找到简明的解释,但无济于事。
此代码确实适用于 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
【问题讨论】: