VBA把所有sheet名称前6位为“Daily&”的A1单元格数据汇总后求出平均值,A2单元格数据汇总后求出平均值,平均值计算忽略空格和0,最后将求出的平均值存入sheet名称为“5月”的A1,A2单元格中
时间: 2023-06-26 13:05:40 浏览: 189
以下是实现此功能的VBA代码:
```
Sub AverageDailyData()
Dim ws As Worksheet
Dim dailyRange As Range
Dim cell As Range
Dim sumA1 As Double
Dim countA1 As Integer
Dim sumA2 As Double
Dim countA2 As Integer
Dim avgA1 As Double
Dim avgA2 As Double
'遍历所有工作表
For Each ws In ThisWorkbook.Worksheets
'判断工作表名称前6位是否为“Daily&”
If Left(ws.Name, 6) = "Daily&" Then
'获取A1单元格数据范围
Set dailyRange = ws.Range("A1:A" & ws.Cells(Rows.Count, 1).End(xlUp).Row)
'遍历A1单元格数据范围
For Each cell In dailyRange
'忽略空格和0,计算A1单元格数据总和和个数
If IsNumeric(cell.Value) And cell.Value <> "" And cell.Value <> 0 Then
sumA1 = sumA1 + cell.Value
countA1 = countA1 + 1
End If
Next cell
'获取A2单元格数据范围
Set dailyRange = ws.Range("A2:A" & ws.Cells(Rows.Count, 1).End(xlUp).Row)
'遍历A2单元格数据范围
For Each cell In dailyRange
'忽略空格和0,计算A2单元格数据总和和个数
If IsNumeric(cell.Value) And cell.Value <> "" And cell.Value <> 0 Then
sumA2 = sumA2 + cell.Value
countA2 = countA2 + 1
End If
Next cell
End If
Next ws
'计算A1和A2的平均值
If countA1 > 0 Then
avgA1 = sumA1 / countA1
End If
If countA2 > 0 Then
avgA2 = sumA2 / countA2
End If
'将平均值写入“5月”工作表的A1和A2单元格中
ThisWorkbook.Worksheets("5月").Range("A1").Value = avgA1
ThisWorkbook.Worksheets("5月").Range("A2").Value = avgA2
End Sub
```
请注意,在运行此代码之前,请务必备份您的工作簿。
阅读全文