【发布时间】:2018-04-14 02:56:34
【问题描述】:
我有以下代码可以根据行的动态范围在特定列的底部运行求和公式。我的限制是我必须定义我希望这发生在哪些列。如何根据其中包含数据的最后一列使其动态化?
谢谢
Option Explicit
Sub Sum()
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
If WS.Name <> "Master" And WS.Name <> "How to" And WS.Name <> "Template" Then
Dim CurCal As XlCalculation
Dim wb As Workbook, colsLastRow As Long
Dim cols As Variant, SumCols As Long, colsArray As Variant
Dim biggestRow As Long
Dim shNAMES As Range
Application.ScreenUpdating = False
CurCal = Application.Calculation
Application.Calculation = xlCalculationManual
biggestRow = 1
Set wb = ThisWorkbook
colsArray = Array("L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ")
For Each cols In colsArray
colsLastRow = WS.Cells(Rows.Count, cols).End(xlUp).Row
If colsLastRow > biggestRow Then
biggestRow = colsLastRow + 1
End If
Next cols
For Each cols In colsArray
colsLastRow = WS.Cells(Rows.Count, cols).End(xlUp).Row
WS.Cells(biggestRow, cols).Formula = "=SUM(" & cols & "9:" & cols & colsLastRow & ")"
Next cols
WS.Range("B" & biggestRow).Value = "TOTAL"
WS.Cells(3, 3).Formula = "=LOOKUP(2,1/(N:N<>""""),N:N)"
Application.ScreenUpdating = True
Application.Calculation = CurCal
End If
Next WS
End Sub
【问题讨论】:
-
你能举个例子吗?在上面的什么地方你会使用最后一列,你是否希望 colArray 保存所有列,包括这个?
-
我有一个表,它是 B 列到(X 列数)的第 9 行到(X 行数)行的数据。对于该列中直到第 9 行的所有数据,我想要在 L 到(可变数量的列)列的最后一行下方有一个求和公式。这些列可能在 z 处结束,也可能在 AZ 处结束。现在我必须准确定义我想要在数组中求和的列。我希望它动态改变。
-
是excel表格吗? IE。一个实际的表格,如果你将一个公式放在一个列中,它会自动填充?
-
是的,只是 excel 中的数据。但我需要跨越一行,而不是一列
-
你打算从第 9 行向下求和?