我正在尝试做一个简单的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
请帮忙!
答案 0 :(得分:2)
您需要循环:
考虑:
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
醇>
答案 1 :(得分:1)
您可以折叠代码:
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