Day39 - 代码优化(2)

今日学习目标

  • 掌握注释编写规范
  • 统一代码风格
  • 完善错误处理机制

知识点

### 1. 注释规范
- 过程注释:功能、参数、返回值说明
- 关键逻辑注释:复杂算法解释
- TODO标记:待完善事项
### 2. 代码风格统一
- 缩进和空格
- 命名规范(驼峰/下划线)
- 括号和换行
### 3. 错误处理策略
- On Error Resume Next vs GoTo
- 错误日志记录
- 用户友好提示

今日代码

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' 过程名:ProcessMonthlyReport
' 功能:生成月度销售报表
' 参数:
'   reportMonth As String - 报表月份,格式YYYY-MM
'   savePath As String - 保存路径
' 返回值:Boolean - True成功,False失败
' 创建日期:2024-01-15
' 修改日期:2024-01-20 - 添加错误处理
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function ProcessMonthlyReport(reportMonth As String, _
                              savePath As String) As Boolean
    On Error GoTo ErrorHandler

    Dim ws As Worksheet
    Dim reportData As Variant
    Dim fileName As String

    ' 初始化
    ProcessMonthlyReport = False

    ' 获取报表数据
    reportData = GetReportData(reportMonth)
    If IsEmpty(reportData) Then
        MsgBox "未找到" & reportMonth & "的数据!", vbExclamation
        Exit Function
    End If

    ' 创建报表
    Set ws = CreateReportSheet(reportMonth)
    Call FillReportData(ws, reportData)

    ' 格式化报表
    Call FormatReport(ws)

    ' 保存报表
    fileName = savePath & "\销售报表_" & reportMonth & ".xlsx"
    Call SaveReport(ws, fileName)

    ProcessMonthlyReport = True
    MsgBox "报表生成成功!", vbInformation

    Exit Function

ErrorHandler:
    ' 记录错误日志
    Call LogError("ProcessMonthlyReport", Err.Number, Err.Description)

    ' 用户提示
    MsgBox "报表生成失败:" & Err.Description, vbCritical

    ProcessMonthlyReport = False
End Function

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' 过程名:LogError
' 功能:记录错误信息到日志文件
' 参数:
'   procName As String - 过程名称
'   errNum As Long - 错误编号
'   errDesc As String - 错误描述
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub LogError(procName As String, errNum As Long, errDesc As String)
    Dim logFile As String
    Dim fileNum As Integer

    logFile = ThisWorkbook.Path & "\error_log.txt"
    fileNum = FreeFile

    Open logFile For Append As #fileNum
    Print #fileNum, Format(Now, "yyyy-mm-dd hh:mm:ss") & _
                     " | " & procName & _
                     " | 错误" & errNum & ": " & errDesc
    Close #fileNum
End Sub

练习题

  1. 为之前编写的过程添加详细注释
  2. 统一所有变量的命名风格
  3. 添加全局错误处理模块