Vba判断从D列开始的日期往右数是否有七天,有就折叠并插入一列计算七天一次每行的汇总
时间: 2024-05-31 19:08:41 浏览: 148
以下是一个实现上述功能的VBA代码:
Sub FoldColumns()
Dim lastCol As Integer
Dim i As Integer
Dim j As Integer
Dim count As Integer
Dim sum As Double
'获取最后一列的列号
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
'从D列开始循环
For i = 4 To lastCol
count = 0
sum = 0
'检查往右数七列是否都有数据
If i + 6 <= lastCol Then
For j = i To i + 6
If Cells(1, j) <> "" Then
count = count + 1
sum = sum + Cells(1, j)
End If
Next j
End If
'如果有七列数据就折叠并插入一列计算七天一次每行的汇总
If count = 7 Then
Columns(i + 1).Insert shift:=xlToRight
Range(Cells(1, i), Cells(1, i + 6)).EntireColumn.Group
Cells(1, i + 1) = "7-Day Sum"
Range(Cells(2, i + 1), Cells(ActiveSheet.UsedRange.Rows.Count, i + 1)) _
.Formula = "=SUM(" & Cells(2, i).Address & ":" & Cells(ActiveSheet.UsedRange.Rows.Count, i + 6).Address & ")"
End If
'跳过已经合并的列
If count = 7 Then
i = i + 1
End If
Next i
End Sub
这段代码首先获取最后一列的列号,然后从D列开始循环,检查往右数七列是否都有数据。如果有,则折叠这七列并插入一列计算七天一次的汇总。最后跳过已经合并的列,继续循环。
阅读全文