简体   繁体   English

在阵列上使用VBA正则表达式

[英]Using VBA regex on Array

I am writing a macro and the macro works fine, but I am trying to add some error handling to it so others are using it and an error occurs they are able to figure out what happened. 我正在编写一个宏,并且该宏工作正常,但是我尝试向其添加一些错误处理,以便其他人正在使用它,并且发生错误时,他们可以弄清楚发生了什么。 The last problem I am having is I am using the Application.GetOpenFilename to open multiple files with multiselect = True. 我遇到的最后一个问题是我正在使用Application.GetOpenFilename以multiselect = True打开多个文件。 I am using a regex to match the file name and if the wrong file name is chosen then it displays an error message. 我正在使用正则表达式来匹配文件名,如果选择了错误的文件名,则会显示错误消息。 If multiselect = False then I get no errors, but when it is equal to True I get a Type Mismatch error. 如果multiselect = False,那么我没有错误,但是当它等于True时,我会收到Type Mismatch错误。 I can only assume this is because when mutliselect = True the file is an array which the regex cannot handle. 我只能假设这是因为当mutliselect = True时,文件是正则表达式无法处理的数组。 Is there a solution to this or can anyone point me to a better solution to handle the error. 是否有解决方案,或者有人可以向我指出解决错误的更好解决方案。 I have attached the VBA script as well. 我还附加了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

When MultiSelect is true, file will always be a variant array, even if only a single file is selected. MultiSelect为true时,即使仅选择一个文件, file也将始终是变量数组。 Therefore you must iterate through each element of the array in order to check it against your mask. 因此,您必须遍历数组的每个元素,以便根据掩码进行检查。

With regard to your mask, I would suggest using the Like operator as it seems simpler and will probably run faster. 关于您的掩码,我建议您使用Like运算符,因为它看起来更简单,并且运行速度可能更快。 Note the # replacing the regex pattern [0-9] ) eg: 注意#替换正则表达式模式[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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM