VBA:收集并在UserForm中显示错误消息?

时间:2019-05-01 10:01:45

标签: excel vba userform

我用VBA编写了一些代码,该代码从其他工作簿中获取数据,然后更新了几个“主文件”,这些代码通过这些文件进行循环。现在,我在更新数据之前进行了备份,并在循环结束时保存了更新的文件。该代码有效,我不确定它与问题的相关性:

Sub YearlyReport()

Dim FilePath As String
Dim VWArray As Variant
Dim wbVWAggr As Workbook
Dim VWNumber As Variant

FilePath = "C:\VBA\YearlyReport\"
VWArray = Array(21, 25, 35, 45, 46, 49, 51, 52, 53, 54, 101)

Application.ScreenUpdating = False
    For Each VWNumber In VWArray
        Set wbVWAggr = Application.Workbooks.Open(FilePath & "Report" & VWNumber & ".xlsx")
        wbVWAggr.SaveAs FilePath & "Report" & VWNumber & "_old" & Format(Now(), "dd-mm-yyyy hh-mm-ss") & ".xlsx"

        'Data gets copy pasted from other workbooks

        Application.DisplayAlerts = False 'Overwrite old file
        wbVWAggr.SaveAs FilePath & "Report" & VWNumber & ".xlsx"
        Application.DisplayAlerts = True
    Next VWNumber

Application.ScreenUpdating = True   
End Sub

这种方法很好,但是如果找不到文件怎么办?我真正想做的是继续执行代码,收集错误消息并在最后显示给用户(我将代码放在单独的子目录中)。我仍然必须编写它,但是然后我可以询问用户他是否要保存或取消整个操作:

Sub ErrorCollection()
    Dim ErrorCount As Long
    Dim ErrorArray() As String
    Dim FilePath As String
    Dim VWNumber As Variant
    Dim VWArray As Variant
    Dim ErrorMessage As String
    Dim Item As Variant

    FilePath = "C:\VBA\YearlyReport\"
    VWArray = Array(21, 25, 35, 45, 46, 49, 51, 52, 53, 54, 101)

    For Each VWNumber In VWArray
        If Dir$(FilePath & "Report" & VWNumber & ".xlsx") = "" Then
            ErrorMessage = "Report" & VWNumber & " cannot be found."
            ReDim Preserve ErrorArray(ErrorCount)
            ErrorArray(ErrorCount) = ErrorMessage
            ErrorCount = ErrorCount + 1
        End If
    Next VWNumber

    If ErrorCount > 0 Then
        MsgBox Join(ErrorArray, vbCrLf)
    End If
End Sub

理想情况下,用户还可以隐藏弹出消息以查看文件,这意味着使用UserForm-但是在那种情况下,如何显示错误消息,如在MsgBox中?我尝试使用谷歌搜索,但只遇到了如何从用户表单填充数组的问题。

0 个答案:

没有答案