【问题标题】:VBA error handling - what are the best practices for the given situation? [closed]VBA 错误处理 - 给定情况的最佳实践是什么? [关闭]
【发布时间】:2012-10-03 15:02:27
【问题描述】:

我有一个程序可以打开许多 Excel 工作簿并将所有这些工作簿中的数据合并到目标工作簿中。合并后,它对数据进行一些转换(使用自定义逻辑将列转置为行),然后使用查找数据添加更多列。

我有以下代码

Sub consolidateFiles()
    On Error GoTO ErrorHandler

    processFiles
    transform
    addLookupData

    Exit Sub
    ErrorHandler:
    Debug.Print Err.Number & " = " & Err.Description & ", Source = " & Err.Source 
End Sub

Sub processFiles()
 'Here I open all the files in the directory and copy and paste into the target workbook. 
 'If there is an error here, I would like to know the file that caused the error 
 'and I would like to proceed to the next file after logging the error
End Sub

Sub transform()
 'Here I transform some of the data from column to year.
End Sub

Sub addLookupData()
 'Here I add some new columns by looking up the data in another sheet in the target  workbook. Here the lookups can return error
End Sub

我想知道在我的代码中添加错误处理的良好编程实践是什么。现在,我有一个全局错误处理程序,它记录错误并继续执行程序。为我从主过程调用的 3 个子过程中的每一个添加错误处理是一个好主意吗?

我阅读了有关使用未记录的 ERL 来获取错误行的信息。我们如何在 VBA 编辑器中添加行号?

这是我在 VBA 中的第一个程序。我做过很多 Java 编程,但是错误处理范式非常不同。因此,我想向有经验的 VBA 程序员学习我可以遵循的良好做法。

我已阅读这篇优秀的文章,该文章链接到与 SO 中的 VBA 错误处理相关的问题之一:

http://www.cpearson.com/excel/errorhandling.htm

【问题讨论】:

  • @SiddharthRout,谢谢 Siddharth。我已经通读了这个帖子以及其中的每一个回复。尽管该线程提供了一些提示,但它并没有完全回答我的问题。我也在阅读您的文章“犯错是人的事”——您能发布一些您遵循的做法吗?
  • 首要任务... 下载 MZ Tools 并安装它。 MZ的链接在上面的链接中:)
  • @SiddharthRout,我已经安装了 MZ Tools 并玩了一下。它添加的错误处理程序会抛出一个 MsgBox,这会使程序在一个错误后停止。我可以自定义它——但这就是我需要帮助的地方,需要遵循哪些良好做法
  • 我和@brettdj 都在上面的链接中介绍了大部分好的做法。但是,如果您向我们展示您现在正在尝试的代码,我们可以在需要时为您提供具体的输入。

标签: excel vba


【解决方案1】:

由于我没有得到任何答案,因此我尝试进行更多研究。以下是我认为有用的一些文章:

http://www.techrepublic.com/blog/five-apps/five-tips-for-handling-errors-in-vba/339

http://www.jpsoftwaretech.com/vba-tips-tricks-and-best-practices-part-four/

http://www.fmsinc.com/tpapers/vbacode/debug.asp#BasicErrorHandling

另外,我发现在每个过程中遵循 SingleExitPoint(有错误或无错误)是一种很好的做法。

许多想法都在 Siddharth 提供的链接中陈述/暗示。但在我阅读这些文章之前,它们对我来说并不是很清楚。

【讨论】:

    猜你喜欢
    • 2010-10-18
    • 2014-11-28
    • 2011-09-22
    • 2013-01-13
    • 2020-06-05
    • 1970-01-01
    • 2011-05-30
    • 2020-12-24
    • 2019-10-03
    相关资源
    最近更新 更多