统一计算当前单元格的所有sheet相加的值,因为导出每堂课的点名名单,对每堂课被点名的学生的分数进行一个求和,两种方式单个、多个。
单个单元格处理
Sub SumValuesAcrossSheets()Dim currentCell As RangeDim total As DoubleDim ws As Worksheet' 获取当前所在单元格Set currentCell = ActiveCell' 初始化总和为零total = 0' 遍历所有工作表For Each ws In ThisWorkbook.Sheets' 检查当前单元格是否包含数字If IsNumeric(currentCell.Value) Then' 将当前单元格的值相加total = total + ws.Range(currentCell.Address).ValueEnd IfNext ws' 在当前单元格输入总和currentCell.Value = total
End Sub
多个单元格处理
Sub SumValuesInRangeAcrossSheets()Dim selectedRange As RangeDim cell As RangeDim total As DoubleDim ws As Worksheet' 获取选中的范围On Error Resume NextSet selectedRange = Application.InputBox("请选择一个范围:", Type:=8)On Error GoTo 0' 检查是否成功选择了范围If selectedRange Is Nothing ThenMsgBox "未选择有效范围。"Exit SubEnd If' 遍历选中范围中的每个单元格For Each cell In selectedRange' 初始化总和为零total = 0' 遍历所有工作表For Each ws In ThisWorkbook.Sheets' 检查当前单元格是否包含数字If IsNumeric(cell.Value) Then' 将当前单元格的值相加total = total + ws.Range(cell.Address).Value' 将当前单元格的值先转换为数字再执行total = total + Val(ws.Range(cell.Address).Value)End IfNext ws' 在当前单元格输入总和cell.Value = totalNext cell
End Sub