宏步计数器

问题描述 投票:0回答:2

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

请帮忙!

excel vba excel-vba
2个回答
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. 我们用字符串常量替换变量Z
  5. 我们为Set删除了StepCounter

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
© www.soinside.com 2019 - 2024. All rights reserved.