如何为 Excel VBA 中的奇数行添加总和值
How to add sum value for odd number rows in Excel VBA
我的 VBA 代码需要帮助,我想获取每个奇数行的总值(显示在 Sheets("Report").Cells(LastLine,i).Value 中。在我的代码中,我只能得到奇数行和偶数行的总值。谢谢!
这是我的 VBA 代码:
'LastLine is a row number which have blank content
Dim LastLine As Long
LastLine = Range("B" & Rows.count).End(xlUp).Row + 2
For i = 4 To 21
Sheets("Report").Cells(LastLine, y).Select
With Selection
.Font.Bold = True
.Font.Size = 10
.Interior.Color = RGB(135, 206, 250)
End With
Sheets("Report").Cells(LastLine, i).Value = WorksheetFunction.Sum(Range(Cells(2, i), Cells(65536, i)))
Next
第一个NEVER use Select
让我们试试这个:
'LastLine is a row number which have blank content
Dim LastLine As Long, RunSum As Long
LastLine = Range("B" & Rows.count).End(xlUp).Row + 2
For i = 4 To 21
With Sheets("Report").Cells(LastLine, y) 'Perhaps (LastLine, i)?
.Font.Bold = True
.Font.Size = 10
.Interior.Color = RGB(135, 206, 250)
End With
RunSum = 0
For CurRow = 3 to LastLine - 1 Step 2
RunSum = RunSum + Cells(CurRow, i).Value
Sheets("Report").Cells(LastLine, i).Value = RunSum
Next CurRow
Next i
我的 VBA 代码需要帮助,我想获取每个奇数行的总值(显示在 Sheets("Report").Cells(LastLine,i).Value 中。在我的代码中,我只能得到奇数行和偶数行的总值。谢谢!
这是我的 VBA 代码:
'LastLine is a row number which have blank content
Dim LastLine As Long
LastLine = Range("B" & Rows.count).End(xlUp).Row + 2
For i = 4 To 21
Sheets("Report").Cells(LastLine, y).Select
With Selection
.Font.Bold = True
.Font.Size = 10
.Interior.Color = RGB(135, 206, 250)
End With
Sheets("Report").Cells(LastLine, i).Value = WorksheetFunction.Sum(Range(Cells(2, i), Cells(65536, i)))
Next
第一个NEVER use Select
让我们试试这个:
'LastLine is a row number which have blank content
Dim LastLine As Long, RunSum As Long
LastLine = Range("B" & Rows.count).End(xlUp).Row + 2
For i = 4 To 21
With Sheets("Report").Cells(LastLine, y) 'Perhaps (LastLine, i)?
.Font.Bold = True
.Font.Size = 10
.Interior.Color = RGB(135, 206, 250)
End With
RunSum = 0
For CurRow = 3 to LastLine - 1 Step 2
RunSum = RunSum + Cells(CurRow, i).Value
Sheets("Report").Cells(LastLine, i).Value = RunSum
Next CurRow
Next i