VBA For循环遇对象不存在错误时,如何实现不终止且继续执行?
解决VBA循环中对象不存在时跳过执行的问题
完全可行!咱们可以通过VBA的错误处理机制来实现这个需求——当找不到CFPvol5对象时,直接跳过它对应的逻辑块,继续执行后面的CFPTr相关代码。
实现思路
核心是针对可能找不到的对象单独做错误捕获:
- 用
On Error Resume Next临时开启“忽略错误”模式,尝试创建目标对象 - 完成对象创建后,立刻用
On Error GoTo 0恢复正常的错误处理(避免后续代码的错误被意外忽略) - 检查对象是否创建成功(判断对象是否为
Nothing),只有创建成功时才执行对应的逻辑代码
修改后的完整代码
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 ' 处理CFPvol5的错误捕获 Dim CFPvol5 As Object ' 确保变量声明,若已有声明可忽略 On Error Resume Next ' 临时开启错误忽略 Set CFPvol5 = class.Vectors("Cashflow DFM JM vol5").Method On Error GoTo 0 ' 恢复正常错误处理 Set CFPTr = class.Vectors("Cashflow DFM JM Tr").Method orig = project.OriginCount For k = 1 To orig ' CFP相关逻辑,不受影响正常执行 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) ' 只有CFPvol5对象存在时,才执行这部分逻辑 If Not CFPvol5 Is Nothing Then 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) End If ' CFPTr相关逻辑,不受影响正常执行 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 ' 清空对象变量,避免循环中残留引用 Set CFPvol5 = Nothing Next
关键细节说明
- 错误处理范围控制:只在
Set CFPvol5这一行临时开启错误忽略,之后立刻恢复正常错误处理,这样其他代码如果出错还是会正常提示,不会被掩盖。 - 对象存在性判断:用
If Not CFPvol5 Is Nothing Then包裹CFPvol5的所有逻辑,确保只有对象存在时才执行。 - 变量清理:在每次外层循环结束后,用
Set CFPvol5 = Nothing清空对象引用,避免下一次循环中误用上一次的对象。
如果后续发现CFP或者CFPTr也可能出现找不到的情况,完全可以套用同样的逻辑,给它们也加上错误捕获和存在性判断~
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

