【问题标题】:VBA: For-Loop should not stop when encountering an error, it should jump to the next blockVBA:For-Loop在遇到错误时不应该停止,它应该跳转到下一个块
【发布时间】:2018-05-17 09:50:25
【问题描述】:

我需要修改一个for循环,以便它在找不到对象时跳到下一次迭代。这是一个sn-p:

For j = 0 To i - 1

  Proj = Cells(3 + j, 2).Value

  ResClass = Cells(3 + j, 3).Value

    Set project = resq.Projects.Item(Proj)
    Set class = project.ReservingClasses(ResClass)

    Set CFP = class.Vectors("Cashflow DFM JM").Method
    Set CFPvol5 = class.Vectors("Cashflow DFM JM vol5").Method
    Set CFPTr = class.Vectors("Cashflow DFM JM Tr").Method

    orig = project.OriginCount 

For k = 1 To orig

            Cells(20 - 3, 4) = "DFM JM"
            Cells(20 - 3, 4).Font.Bold = True
            Cells(20 + k, col) = CFP.CashFlowPeriodLabel(k) - orig
            Cells(20 - 2, col) = Cells(3 + j, 1).Value
            Cells(20 - 2, col).Font.Bold = True
            Cells(20 - 1, col + 1) = CFP.CashFlowPeriodLabel(1)
            Cells(20 + k, col + 1) = Round(CFP.DiscountedCashflows(k, 1), 0)
            Cells(20 - 1, col + 2) = CFP.CashFlowPeriodLabel(2)
            Cells(20 + k, col + 2) = Round(CFP.DiscountedCashflows(k, 2), 0)

            Cells(59 - 3, 4) = "DFM Paid vol5"
            Cells(59 - 3, 4).Font.Bold = True
            Cells(59 + k, col) = CFPvol5.CashFlowPeriodLabel(k) - orig
            Cells(59 - 2, col) = Cells(3 + j, 1).Value
            Cells(59 - 2, col).Font.Bold = True
            Cells(59 - 1, col + 1) = CFPvol5.CashFlowPeriodLabel(1)
            Cells(59 + k, col + 1) = Round(CFPvol5.DiscountedCashflows(k, 1), 0)
            Cells(59 - 1, col + 2) = CFPvol5.CashFlowPeriodLabel(2)
            Cells(59 + k, col + 2) = Round(CFPvol5.DiscountedCashflows(k, 2), 0)

            Cells(98 - 3, 4) = "DFM JM Tr"
            Cells(98 - 3, 4).Font.Bold = True
            Cells(98 + k, col) = CFPTr.CashFlowPeriodLabel(k) - orig
            Cells(98 - 2, col) = Cells(3 + j, 1).Value
            Cells(98 - 2, col).Font.Bold = True
            Cells(98 - 1, col + 1) = CFPTr.CashFlowPeriodLabel(1)
            Cells(98 + k, col + 1) = Round(CFPTr.DiscountedCashflows(k, 1), 0)
            Cells(98 - 1, col + 2) = CFPTr.CashFlowPeriodLabel(2)
            Cells(98 + k, col + 2) = Round(CFPTr.DiscountedCashflows(k, 2), 0)

Next k
    col = col + 4


Next

如果对于第一个 for 循环中的某个 j,第二个 for 循环中没有 CFPvol5,则该过程会因错误而停止。我希望程序继续下一个块,在这种情况下是 CFPTr。这可能吗?如果是,如何?

非常感谢您的帮助!

【问题讨论】:

  • 你为什么要循环使用Cells(20 - 3, 4) = "DFM JM"这样的命令?它们独立于循环和迭代器值。它只是增加了额外的计算(一次就足够了)。
  • 很好的提示:我会把它们带出循环。

标签: vba excel loops for-loop


【解决方案1】:

显示了 2 种方法:只是一个示例。

 on error resume next

         For i = 1 to x
        'do your stuff here

        next

        on error goto 0

on error goto nextLoop
for i = 1 to x

' do your stuff here

nextLoop:
next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 2015-01-14
    • 2014-07-07
    • 2023-01-31
    • 2015-04-17
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多