如何调整宏中COUNTIF/SUMIF公式以动态引用整列数据?
动态适配行数的运费重算汇总工具优化需求
我正在为团队制作一款行项目运费重算工具,已基本完成,希望添加数据汇总功能减少手动操作。刚接触VBA,目前依赖宏录制生成代码后修改,暂无法用VBA创建数据透视表,因此使用了SUMIF和COUNTIF公式。当前公式仅适配固定行数(测试数据为64行),但数据行数会随运单数量变化,列标题固定。我不想用超大行数引用担心影响性能,希望调整公式以动态引用整列;同时也希望了解更简洁的动态实现方案。
现有宏代码如下:
Sub TestTable() ' ' TestTable Macro ' ' Keyboard Shortcut: Ctrl+t 'Summary Sheet 'Naming Summary Columns Worksheets("Summary").Select Range("B3").Select ActiveCell.FormulaR1C1 = "Mail Class" Range("C3").Select ActiveCell.FormulaR1C1 = "Count of Postage" Range("D3").Select ActiveCell.FormulaR1C1 = "Sum of Postage" Range("E3").Select ActiveCell.FormulaR1C1 = "Sum of Rerate" Range("F3").Select ActiveCell.FormulaR1C1 = "Sum of Difference" 'List unique Mail Classes Worksheets("Summary").Select Range("B4").Select ActiveCell.FormulaR1C1 = _ "Ground Advantage" Range("B5").Select ActiveCell.FormulaR1C1 = _ "Priority" 'Count Unique Mail Classes Range("C4").Select ActiveCell.FormulaR1C1 = _ "=COUNTIF('Test Sheet'!R3C1:R64C1,""Ground Advantage"")" Range("C5").Select ActiveCell.FormulaR1C1 = "=COUNTIF('Test Sheet'!R3C1:R64C1,""Priority"")" Range("C3").Select ' Sum of Postage Range("D4").Select ActiveCell.FormulaR1C1 = _ "=SUMIF('Test Sheet'!R3C1:R64C1,""Ground Advantage"",'Test Sheet'!R3C4:R64C4)" Range("D5").Select ActiveCell.FormulaR1C1 = _ "=SUMIF('Test Sheet'!R3C1:R64C1,""Priority"",'Test Sheet'!R3C4:R64C4)" 'Sum of Rerate Range("E4").Select ActiveCell.FormulaR1C1 = _ "=SUMIF('Test Sheet'!R3C1:R64C1,""Ground Advantage"",'Test Sheet'!R3C5:R64C5)" Range("E5").Select ActiveCell.FormulaR1C1 = _ "=SUMIF('Test Sheet'!R3C1:R64C1,""Priority"",'Test Sheet'!R3C5:R64C5)" 'Sum of Difference Range("F4").Select ActiveCell.FormulaR1C1 = _ "=SUMIF('Test Sheet'!R3C1:R64C1,""Ground Advantage"",'Test Sheet'!R3C6:R64C6)" Range("F5").Select ActiveCell.FormulaR1C1 = _ "=SUMIF('Test Sheet'!R3C1:R64C1,""Priority"",'Test Sheet'!R3C6:R64C6)" 'Column Totals Range("C6").Select ActiveCell.FormulaR1C1 = _ "=SUM('Summary'!R4C3:R5C3)" Range("D6").Select ActiveCell.FormulaR1C1 = _ "=SUM('Summary'!R4C4:R5C4)" Range("E6").Select ActiveCell.FormulaR1C1 = _ "=SUM('Summary'!R4C5:R5C5)" Range("F6").Select ActiveCell.FormulaR1C1 = _ "=SUM('Summary'!R4C6:R5C6)" Range("G6").Select ActiveCell.FormulaR1C1 = _ "Grand Total" 'Formatting Cells and Data type Cells.Select Cells.EntireColumn.AutoFit Range("D4:F6").Select Selection.Style = "Currency" Range("C3").Select End Sub
注:“Column Totals”部分为静态汇总输出,无需修改。
内容的提问来源于stack exchange,提问作者Paulonious1
相关产品推荐
相关产品推荐

