我有一个程序可以打开许多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错误处理相关的一个问题相关联:
答案 0 :(得分: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提供的链接中陈述/暗示了许多想法。但在我阅读这些文章之前,他们并不是很清楚。