带dynamic范围和variables的VBA Excel公式

我想在VBA中做一个dynamic的总和公式,这对我来说是非常困难的,因为我没有使用好的整数variables。 最后一行可能会在将来改变,我需要这个范围是dynamic的。 感谢那些会帮助我的人。

Sub SumColumns() Sheets("data").Select Range("A1").End(xlDown).Offset(1, 0).Select Selection.Value = "sum" Selection.Interior.ColorIndex = 33 Selection.Font.Bold = True Dim LastCol As Integer Dim LastRow As Integer With Sheets("data") LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column End With Range("A1").End(xlDown).Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=SUM(R[- " & LastRow & " + 1]C:R[-1]C)" Selection.AutoFill Destination:=Range("B" & LastRow, "I" & LastRow), Type:=xlFillDefault End Sub 

那是错误的行:

 ActiveCell.FormulaR1C1 = "=SUM(R[- " & LastRow & " + 1]C:R[-1]C)" 

取出引号中的+1,因为这似乎是导致问题,你需要扣除1,否则你将在第零行。 下面的代码也会删除你不需要的和低效的select。 并使用您的LastColvariables来确定复制公式的列数。

 Sub SumColumns() Dim LastCol As Long 'use Long rather than Integer Dim LastRow As Long With Sheets("data") LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row With .Range("A" & LastRow + 1) .Value = "sum" .Interior.ColorIndex = 33 .Font.Bold = True End With LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column .Range("B" & LastRow + 1).Resize(, LastCol - 1).FormulaR1C1 = "=SUM(R[-" & LastRow - 1 & "]C:R[-1]C)" End With End Sub 

您可以摆脱许多select部分和蒸汽线代码如下。 testing一下,看看这是你以后的样子。

  Sub SumColumns() Dim LastCol As Long Dim LastRow As Long With Sheets("data") LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column With .Range("A" & LastRow).Offset(1, 0) .Value = "SUM" .Interior.ColorIndex = 33 .Font.Bold = True End With LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row .Range("A" & LastRow).Offset(0, 1).FormulaR1C1 = "=SUM(R[-" & LastRow - 1 & "]C:R[-1]C)" .Range("A" & LastRow).Offset(0, 1).AutoFill Destination:=.Range("B" & LastRow, .Cells(LastRow, LastCol)), Type:=xlFillDefault .Range("A" & LastRow, .Cells(LastRow, LastCol)).Borders.LineStyle = xlContinuous .Range("A" & LastRow, .Cells(LastRow, LastCol)).Borders.Weight = xlThin End With End Sub