Excel表有14行数据,其中2到14行数据已经存在,行数固定,但列数不一定,A列为标题,现需使用Vba实现以下操作: 1.在第一行求对应列2到14行的和, 2.用3到14行依次减对应列的第二行数据,直到减完第二行的数为止,即数据不会出现负数 用函数表示逻辑B1=SUM(B2:B14),B2=IF(SUM(B3:B14)<B2,SUM(B3:B14),B2),B3=IF(B$3-B$2>0,B$3-B$2,0),B4=IF(SUM(B$3:B3)-B$2>0,B4,IF(SUM(B$3:B4)-B$2<=0,0,SUM(B$3:B4)-B$2))
时间: 2024-02-24 09:54:06 浏览: 27
以下是 VBA 代码实现:
1. 在第一行求对应列2到14行的和:
```VBA
Sub CalculateSum()
Dim lastCol As Integer
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column ' 获取最后一列的列号
For i = 2 To lastCol
Cells(1, i).Value = WorksheetFunction.Sum(Range(Cells(2, i), Cells(14, i))) ' 求和并写入第一行
Next i
End Sub
```
2. 用3到14行依次减对应列的第二行数据,直到减完第二行的数为止:
```VBA
Sub CalculateDifference()
Dim lastCol As Integer
Dim currentSum As Double
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column ' 获取最后一列的列号
For i = 2 To lastCol
currentSum = WorksheetFunction.Sum(Range(Cells(3, i), Cells(14, i))) ' 计算第三行到最后一行的和
Do While currentSum > Cells(2, i) ' 当和大于第二行的数据时
currentSum = currentSum - Cells(2, i) ' 减去第二行的数据
Loop
' 将计算结果写入第三行到最后一行
For j = 3 To 14
If j = 3 Then
Cells(j, i).Value = WorksheetFunction.Max(currentSum - Cells(2, i), 0) ' 计算第三行的数据
Else
currentSum = currentSum - Cells(j - 1, i) ' 减去上一行的数据
If currentSum > 0 Then
Cells(j, i).Value = currentSum ' 当和大于0时,写入当前和
Else
Cells(j, i).Value = 0 ' 当和小于等于0时,写入0
End If
End If
Next j
Next i
End Sub
```