VBA总和范围与VBA不工作?

我正在写一个小的macros,它会显示他们之前做一些计算,但我的macros中的“总和”function似乎没有工作?

sub CompileDashboard() For i = 3 To 100 If Sheets(1).Cells(i, "A").Value = "Week 36" Then Sheets(2).Cells(1, 1) = Application.WorksheetFunction.Sum(Range(Cells(i, "AN"), Cells(i, "BF"))) End If Next End sub 

这是简单的步骤,不工作,我不知道为什么它不是总结? 尽pipe值在范围内,它始终输出为0。

正如在注释中提到的那样:

Sheets(2).Cells(1, 1) = Application.WorksheetFunction.Sum(Range(Cells(i, "AN"), Cells(i, "BF")))

需要改变

Sheets(2).Cells(i, 1) = Application.WorksheetFunction.Sum(Range(Cells(i, "AN"), Cells(i, "BF")))

只是一个变化的主题。 我真的很喜欢这个语法,但你永远不会看到它。

 Sub CompileDashboard() Dim i As Integer With Sheets(1) For i = 3 To 100 With .Rows(i) If .Columns("A").Value = "Week 36" Then Sheets(2).Cells(i, 1) = Application.Sum(.Columns("AN:BF")) End If End With Next End With End Sub 

始终为所有Range和Range.Cells对象提供显式的.Parent工作表引用。 A With … End With语句可以轻松完成此操作,不仅可以清理代码,还可以使其运行得更快。

 sub CompileDashboard() with Sheets(1) For i = 3 To 100 If .Cells(i, "A").Value = "Week 36" Then Sheets(2).Cells(1, 1) = Application.Sum(.Range(.Cells(i, "AN"), .Cells(i, "BF"))) End If Next end with End sub 

你的循环的目的不明确。 如果“第36周”只有一行,那么一旦findFor … Next语句,就应该退出; 实际上, Application.Match(...)会立即find它。 如果“第36周”中有多行,则不应覆盖Sheet2上的同一单元格。

如果您打算为“AN”和“BF”之间的所有列汇总行(从Sheets(1) ),则修改您的行:

 Sheets(2).Cells(1, 1) = Application.WorksheetFunction.Sum(Range(Cells(i, "AN"), Cells(i, "BF"))) 

至:

 Sheets(2).Cells(1, 1) = Application.WorksheetFunction.Sum(Sheets(1).Range("AN" & i & ":BF" & i))