运行完了excel的三个工作表的结果一样,问题在哪呢?
代码如下:
Sub 计算成绩()
' 计算成绩 Macro
'i为工作表行号
Dim i, m, total As Integer
Dim w1 As Worksheet
For m = 1 To Worksheets.count
Set w1 = Worksheets(m)
i = 2
total = 0
Do While w1.Cells(i, 2) <> ""
total = total + Cells(i, 2)
i = i + 1
Loop
w1.Cells(2, 3) = total
Next m
End Sub
在这个的代码中,累计这一行有问题,
total=total+cells(i,2)
cells没有指定是哪个工作表的,运行的时候就会按活动工作表activesheet来计,这样每个工作表都是这么运行一遍,累计的都是当前activesheet的数,结果自然都是一样的。有两种改法:
1.指定累计工作表
total=total+w1.cells(i,2)
2.变更活动工作表,添加一行代码
w1.activate
'==代码,已将可修改的做加粗显示=============
Sub 计算成绩()
' 计算成绩 Macro
'i为工作表行号
Dim i As Integer, m As Integer, total As Integer
Dim w1 As Worksheet
For m = 1 To Worksheets.count
Set w1 = Worksheets(m)
w1.Activate
i = 2
total = 0
Do While w1.Cells(i, 2) <> ""
total = total + w1.Cells(i, 2)
i = i + 1
Loop
w1.Cells(2, 3) = total
Next m
End Sub