宏步计数器

时间:2018-02-28 20:32:58

标签: excel vba excel-vba

我正在尝试做一个简单的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

请帮忙!

2 个答案:

答案 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

备注:

  1. 我们定义了一个worksheet对象和Set
  2. 我们创建了一个While循环(因为IF不会自行循环)
  3. 我们颠倒了Cells()
  4. 中的论据
  5. 我们用字符串常量
  6. 替换了变量Z
  7. 我们删除了Set
  8. 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