Tôi nhận được cuốn sách "Phát triển Excel chuyên nghiệp" của Rob Bovey và nó đang mở mắt.Xử lý lỗi Excel VBA - đặc biệt là trong các chức năng - Phong cách phát triển Excel chuyên nghiệp
Tôi đang sửa mã của mình bằng cách xử lý lỗi. Tuy nhiên, có rất nhiều điều tôi không hiểu. Tôi đặc biệt cần phải biết cách sử dụng nó một cách chính xác trong các chức năng. Tôi sử dụng phiên bản rethrow của Bovey của trình xử lý lỗi (ở dưới cùng). Khi tôi bắt đầu, tôi đã sử dụng phương thức boolean (non-rethrow) cơ bản và chuyển các chương trình con của tôi thành các hàm boolean. (P.S. Tôi đang chuyển về phương thức boolean dựa trên câu trả lời.)
Tôi cần hướng dẫn về cách phù hợp với các chức năng trong lược đồ này. Tôi muốn họ trả lại giá trị thực của họ (một chuỗi hoặc gấp đôi, ví dụ, hoặc -1 nếu chúng thất bại trong một số trường hợp) để tôi có thể lồng chúng vào các chức năng khác và không chỉ trả về lỗi xử lý boolean.
Đây là những gì mà một cuộc gọi thường trình con của bDrawCellBorders (myWS) sẽ giống như trong một điểm vào. Các cuộc gọi phụ dường như hoạt động tốt. (Tức là nó là một chương trình con đã được biến thành một chức năng duy nhất để nó có thể trả về một boolean để chương trình xử lý lỗi.)
Sub UpdateMe() ' Entry Point
Const sSOURCE As String = "UpdateMe()"
On Error GoTo ErrorHandler
Set myWS = ActiveCell.Worksheet
Set myRange = ActiveCell
myWS.Unprotect
' lots of code
If Not bDrawCellBorders(myWS) Then ERR.Raise glHANDLED_ERROR ' Call subroutine
' lots of code
ErrorExit:
On Error Resume Next
Application.EnableEvents = True
myWS.Protect AllowFormattingColumns:=True
Exit Sub
ErrorHandler:
If bCentralErrorHandler(msMODULE, sSOURCE,,True) Then ' Call as Entry Point
Stop
Resume
Else
Resume ErrorExit
End If
End Sub
Tuy nhiên, tôi không biết làm thế nào để mở rộng này để chức năng thực sự. Điều này dựa trên một ví dụ trong cuốn sách được vẽ cho một chương trình con, và tôi chỉ chuyển nó sang một hàm. Câu hỏi: * Làm cách nào để gọi? Có phải đơn giản là x = sngDoSomeMath (17) * Chức năng xử lý lỗi của nó có đúng không? * Đâu là địa điểm hoặc địa điểm phù hợp để gọi quy trình xử lý lỗi với bReThrow = true?
Public Function sngDoSomeMath(ByVal iNum As Integer) As Single
Dim sngResult As Single
Const sSOURCE As String = "sngDoSomeMath()"
On Error GoTo ErrorHandler
' example 1, input did not pass validation. don't want to
' go up the error stack but just inform the
' calling program that they didn't get a good result from this
' function call so they can do something else
If iNum <> 42 Then
sngResult = -1 'function failed because I only like the number 42
GoTo ExitHere
End If
' example 2, true error generated
sngResult = iNum/0
sngDoSomeMath = lResult
ExitHere:
Exit Function
ErrorHandler:
' Run cleanup code
' ... here if any
' Then do error handling
If bCentralErrorHandler(msMODULE, sSOURCE, , , True) Then ' The true is for RETHROW
Stop
Resume
End If
End Function
Các Lỗi Handler Routine:
'
' Description: This module contains the central error
' handler and related constant declarations.
'
' Authors: Rob Bovey, www.appspro.com
' Stephen Bullen, www.oaltd.co.uk
'
' Chapter Change Overview
' Ch# Comment
' --------------------------------------------------------------
' 15 Initial version
'
Option Explicit
Option Private Module
' **************************************************************
' Global Constant Declarations Follow
' **************************************************************
Public Const gbDEBUG_MODE As Boolean = False ' True enables debug mode, False disables it.
Public Const glHANDLED_ERROR As Long = 9999 ' Run-time error number for our custom errors.
Public Const glUSER_CANCEL As Long = 18 ' The error number generated when the user cancels program execution.
' **************************************************************
' Module Constant Declarations Follow
' **************************************************************
Private Const msSILENT_ERROR As String = "UserCancel" ' Used by the central error handler to bail out silently on user cancel.
Private Const msFILE_ERROR_LOG As String = "Error.log" ' The name of the file where error messages will be logged to.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Comments: This is the central error handling procedure for the
' program. It logs and displays any run-time errors
' that occur during program execution.
'
' Arguments: sModule The module in which the error occured.
' sProc The procedure in which the error occured.
' sFile (Optional) For multiple-workbook
' projects this is the name of the
' workbook in which the error occured.
' bEntryPoint (Optional) True if this call is
' being made from an entry point
' procedure. If so, an error message
' will be displayed to the user.
'
' Returns: Boolean True if the program is in debug
' mode, False if it is not.
'
' Date Developer Chap Action
' --------------------------------------------------------------
' 03/30/08 Rob Bovey Ch15 Initial version
'
Public Function bCentralErrorHandler(_
ByVal sModule As String, _
ByVal sProc As String, _
Optional ByVal sFile As String, _
Optional ByVal bEntryPoint As Boolean, _
Optional ByVal bReThrow As Boolean = True) As Boolean
Static sErrMsg As String
Dim iFile As Integer
Dim lErrNum As Long
Dim sFullSource As String
Dim sPath As String
Dim sLogText As String
' Grab the error info before it's cleared by
' On Error Resume Next below.
lErrNum = ERR.Number
' If this is a user cancel, set the silent error flag
' message. This will cause the error to be ignored.
If lErrNum = glUSER_CANCEL Then sErrMsg = msSILENT_ERROR
' If this is the originating error, the static error
' message variable will be empty. In that case, store
' the originating error message in the static variable.
If Len(sErrMsg) = 0 Then sErrMsg = ERR.Description
' We cannot allow errors in the central error handler.
On Error Resume Next
' Load the default filename if required.
If Len(sFile) = 0 Then sFile = ThisWorkbook.Name
' Get the application directory.
sPath = ThisWorkbook.Path
If Right$(sPath, 1) <> "\" Then sPath = sPath & "\"
' Construct the fully-qualified error source name.
sFullSource = "[" & sFile & "]" & sModule & "." & sProc
' Create the error text to be logged.
sLogText = " " & sFullSource & ", Error " & _
CStr(lErrNum) & ": " & sErrMsg
' Open the log file, write out the error information and
' close the log file.
iFile = FreeFile()
Open sPath & msFILE_ERROR_LOG For Append As #iFile
Print #iFile, Format$(Now(), "mm/dd/yy hh:mm:ss"); sLogText
If bEntryPoint Or Not bReThrow Then Print #iFile,
Close #iFile
' Do not display or debug silent errors.
If sErrMsg <> msSILENT_ERROR Then
' Show the error message when we reach the entry point
' procedure or immediately if we are in debug mode.
If bEntryPoint Or gbDEBUG_MODE Then
Application.ScreenUpdating = True
MsgBox sErrMsg, vbCritical, gsAPP_NAME
' Clear the static error message variable once
' we've reached the entry point so that we're ready
' to handle the next error.
sErrMsg = vbNullString
End If
' The return vale is the debug mode status.
bCentralErrorHandler = gbDEBUG_MODE
Else
' If this is a silent error, clear the static error
' message variable when we reach the entry point.
If bEntryPoint Then sErrMsg = vbNullString
bCentralErrorHandler = False
End If
'If we're using re-throw error handling,
'this is not the entry point and we're not debugging,
're-raise the error, to be caught in the next procedure
'up the call stack.
'Procedures that handle their own errors can call the
'central error handler with bReThrow = False to log the
'error, but not re-raise it.
If bReThrow Then
If Not bEntryPoint And Not gbDEBUG_MODE Then
On Error GoTo 0
ERR.Raise lErrNum, sFullSource, sErrMsg
End If
Else
'Error is being logged and handled,
'so clear the static error message variable
sErrMsg = vbNullString
End If
End Function
MZ-Tools là một công cụ tuyệt vời. Tôi đã thay thế ErrorHandler đơn giản chuẩn của họ bằng phiên bản Rob Bovey (ở trên). Với ONE CLICK tôi có thể dán tiêu đề và xử lý lỗi vào một thói quen, ngay cả khi tôi bỏ bê để bắt đầu với họ.Nhưng tôi cần thêm thông tin cụ thể về xử lý lỗi hàng đầu cho các chức năng! Cảm ơn. –
+ 1 Đề xuất tốt về Công cụ MZ :) –
Cảm ơn các bạn, nhưng tôi vẫn hy vọng một người nào đó sử dụng các phương pháp được mô tả sẽ kêu vang và làm thẳng tôi ra! Các ví dụ trên trang web đó và trang web đi kèm với MZ-Tools quá cơ bản (tôi đã thay thế chúng trong các tùy chọn MZ-Tools.) –