VBA使用相同行中单元格的求和公式。 行号会随着每个循环而改变

我正在使用VBA从一个网站使用循环提取数字。 我有这些数字导入列F和G.我试图在我的VBA中包括一行,这将允许我使用总和公式添加这两个单元格,并在E列结果。数字将始终在同一行,但在F和G列。

我可以用这种方式使用(ActiveCell.Row)函数吗? 或者应该在我的循环结尾使用If函数。

Range("E" & (ActiveCell.Row)).Formula = "=SUM("Range("F" & (ActiveCell.Row)) & Range("G" & (ActiveCell.Row))")" 

在forumla不使用Range(),因为它不会返回一个string。 而且,您忘记了操作员,您需要在Forumla中添加“+”或“:”

 Range("E" & (ActiveCell.Row)).Formula = "=SUM(F" & ActiveCell.Row & "+" & "G" & ActiveCell.Row & ")" 

否则,您将需要访问forumla中Ranges的Address方法(这是一种浪费,因为您已经input了地址)

但为了清晰起见,下面的代码演示了我的意思:

 Range("E" & (ActiveCell.Row)).Formula = "=SUM(" & Range("F" & (ActiveCell.Row)).Address(False,False) & ":" & Range("G" & (ActiveCell.Row)).Address(False,False) & ")" 

我把这些数字inputF和G列。

如果你想在Col E中插入公式,那就用这个。 这将在Col E的所有相关单元格中一次性input公式。

看到这个例子

 Sub Sample() Dim lRow As Long Dim ws As Worksheet '~~> Change this to the releavnt sheet name Set ws = ThisWorkbook.Sheets("Sheet1") With ws '~~> Find Last row in col E which has data lRow = .Range("E" & .Rows.Count).End(xlUp).Row '~~> This will put the formula from E1 to E last row .Range("E1:E" & lRow).Formula = "=SUM(F1+G1)" End With End Sub