我正在尝试做一个简单的VBA步骤计数器,它总结一列,直到该列加起来为正数。基本上这些是现金流量,可以计算现金何时收支平衡。我只是试图从Z13开始添加单元格,直到Total变为正数(现金流的第一年为负数)。我得到了一个
“所需对象”
运行此代码时出错:
Sub Breakeven()
Dim Total As Long
Dim StepCounter As Integer
Total = Range("z13").Value
Set StepCounter = 14
If Total < 0 Then
Total = Total + CashFlows.Cells(Z, StepCounter).Value
StepCounter = StepCounter + 1
End If
MsgBox "The breakeven is " & Total
End Sub
请帮忙!
你需要一个循环:
考虑:
Sub Breakeven()
Dim Total As Long
Dim StepCounter As Integer
Dim CashFlows As Worksheet
Set CashFlows = ActiveSheet
Total = Range("z13").Value
StepCounter = 14
While Total < 0
Total = Total + CashFlows.Cells(StepCounter, "Z").Value
StepCounter = StepCounter + 1
Wend
MsgBox "The breakeven is " & Total
End Sub
笔记:
worksheet
对象和Set
它While
循环(因为IF
不会自行循环)Cells()
的论点Z
Set
删除了StepCounter
您可以将代码折叠为:
Sub Main()
Dim StepCounter As Long
Do
StepCounter = StepCounter + 1
Loop While WorkSheetFunction.Sum(Range("Z13").Resize(StepCounter) ) < 0
MsgBox "The breakeven is " & WorkSheetFunction.Sum(Range("Z13").Resize(StepCounter) )
End Sub