如何使此数组代码正确输出到我的消息框中?

时间:2019-02-26 16:37:53

标签: excel vba

我有一个电子表格,用户可以与该电子表格进行交互,以指定4个不同文件的文件路径,这些文件需要打开才能运行一些宏。该代码包括检查以查看他们输入的文件路径是否有效(效果很好)。但是,我想做的是,如果有任何不起作用的情况出现一个消息框,然后告诉用户哪一个不起作用。

我的代码确实做到了这一点(尽管我认为这很复杂),但是由于将数组设置为4个值,这意味着如果最终文件不存在,它将在消息中向下四行开始框而不是顶部。

我认为我想做的是MsgBox仅包含丢失文件数量的数组,以使Sub Open_month_0() On Error GoTo ErrHand ThisWorkbook.ActiveSheet.Calculate Dim i As String Dim j As String Dim k As String Dim l As String Dim m As String Dim n As String Dim o As String Dim p As String Dim arr(4) As Variant Dim File_Missing As Integer 'Used as a counter to prompt either an error or successful result File_Missing = 0 i = Range("LUX_Full_file_path") j = Range("LUX_Full_file_name") k = Range("JUP_Full_file_path_M") l = Range("JUP_Full_file_name_M") m = Range("JUP_Full_file_path_Q") n = Range("JUP_Full_file_name_Q") o = Range("JUP_Full_file_path_A") p = Range("JUP_Full_file_name_A") 'The if not's check to see if the file path is valid. If it isn't, gets added to array and File_missing begins If Not Dir(i, vbDirectory) = vbNullString Then Workbooks.Open (i) Windows(j).Visible = False Else arr(1) = "Lux file" File_Missing = File_Missing + 1 End If If Not Dir(k, vbDirectory) = vbNullString Then Workbooks.Open (k) Windows(l).Visible = False Else arr(2) = "Monthly file" File_Missing = File_Missing + 1 End If If Not Dir(m, vbDirectory) = vbNullString Then Workbooks.Open (m) Windows(n).Visible = False Else arr(3) = "Quarterly file" File_Missing = File_Missing + 1 End If If Not Dir(o, vbDirectory) = vbNullString Then Workbooks.Open (o) Windows(p).Visible = False Else arr(4) = "Annual file" File_Missing = File_Missing + 1 End If 'Basic error handling procedure that retains function. If File_Missing > 0 Then MsgBox ("The following files could not be found. Please check the file paths and try again" & vbCrLf & Join(arr, vbCrLf)) Else MsgBox "Files opened successfully." End If Exit Sub ErrHand: MsgBox "There has been a critical error with opening the chosen workbooks. If the problem persists, please contact your administrator for assistance." End Sub 不在第一句话下面3个空行。我有点想通了,但我无法正常工作,现在我很困惑。

CaseIterable

编辑图片:

消息框当前输出的屏幕截图
A screenshot of the message box current output

我希望消息框看起来如何
How I'd like the message box to look

1 个答案:

答案 0 :(得分:1)

由于您以后仅使用该数组来Join,因此您也可以只使用String变量MyMissingFiles代替该数组并附加文件名。

如果您对此数字不感兴趣,甚至不需要计算File_Missing中的文件。

Dim MyMissingFiles As String

If Not Dir(i, vbDirectory) = vbNullString Then
    Workbooks.Open (i)
    Windows(j).Visible = False
Else
    MyMissingFiles = MyMissingFiles & vbCrLf & "Lux file"
End If

' … all the others accordingly here …

If MyMissingFiles <> vbNullString Then
    MsgBox ("The following files could not be found. Please check the file paths and try again" & MyMissingFiles)
Else
    MsgBox "Files opened successfully."
End If