在Array上使用VBA正则expression式

我正在写一个macros和macros工作正常,但我正在尝试添加一些error handling,以便其他人正在使用它,并发生错误,他们能够找出发生了什么事。 我遇到的最后一个问题是我正在使用Application.GetOpenFilename打开multiselect = True的多个文件。 我正在使用正则expression式来匹配文件名,如果select了错误的文件名,则会显示错误消息。 如果multiselect = False,那么我没有得到任何错误,但是当它等于True时,我得到一个Type Mismatch错误。 我只能假设这是因为当mutliselect = True时,文件是正则expression式无法处理的数组。 有没有解决这个问题,或者任何人都可以指出我更好的解决scheme来处理错误。 我也附加了VBA脚本。

 Sub DataImport_Loop() Dim nom As String Dim wb As Excel.Workbook Dim i, j, k, m, n, file As Variant Dim strPattern As String: strPattern = "Strain End Point [0-9] - FEA Loop - Loading - (Timed)" 'File Pattern Dim regex As Object Set regex = CreateObject("VBScript.RegExp") 'Turns Screen Updating and Alert Displays off Application.ScreenUpdating = False Application.DisplayAlerts = False nom = ActiveWorkbook.Name 'takes user straight into necessary folder If CurDir() <> CurDir("J:") Then ChDrive "J:" ChDir "J:FEA Material Data" End If 'Number of specimens tested For i = 1 To 5 'Allows user to select multiple files to open file = Application.GetOpenFilename( _ FileFilter:="Text Files (*.csv), *.csv", _ MultiSelect:=True) 'If no file selected, stop data import and display error message If Not IsArray(file) Then MsgBox ("You only imported " & (i - 1) & " Specimens.") Exit Sub 'Sets patteren to check if correct file With regex .Pattern = strPattern End With 'Checks set pattern, displays error message if not correct file If regex.Test(file) = False Then MsgBox ("Select Loading Only") Exit Sub End If Else Counter = 1 While Counter <= UBound(file) j = (2 * i) - 1 Workbooks.Open file(Counter) Set wb = Workbooks("Strain End Point " & Counter & " - FEA Loop - Loading - (Timed).csv") 'End of column, needs + 3 to account for first 3 unused cells k = Range("F4", Range("F4").End(xlDown)).Count + 3 'Loops through data, deletes negative values For m = 4 To k If Range("F" & m).value < 0 Or Range("F" & m).Offset(0, 1) < 0 Then Range("F" & m).Delete Range("F" & m).Offset(0, 1).Delete 'If cell is deleted, rechecks new value m = m - 1 End If Next m Range("F4:G" & k).Copy Workbooks(nom).Sheets(Counter + 1).Cells(4, j).PasteSpecial wb.Close 'Opens next file Counter = Counter + 1 Wend End If Next i 'Turns Screen Updating and Alert Displays back on Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub 

MultiSelect为true时,即使只select一个文件, file也将始终是变体数组。 因此,您必须遍历数组的每个元素,以便根据您的掩码进行检查。

关于你的面具,我会build议使用Like运算符,因为它似乎更简单,可能会运行得更快。 请注意#replace正则expression式[0-9]例如:

 'Checks set pattern, displays error message if not correct file Const strPattern as String = "Strain End Point # - FEA Loop - Loading - (Timed)" 'File Pattern For I = LBound(file) To UBound(file) If Not file(I) Like strPattern Then MsgBox ("Select Loading Only") Exit Sub End If Next I