VBA中If语句中的通配符数组

时间:2017-09-28 23:35:22

标签: arrays excel vba wildcard

我想用这段代码做的是:

  1. 浏览指定文件夹中的所有文件以及该文件夹中的所有子文件夹。 (该文件夹中的文件通常用下划线分为5个部分。例如," XX1_XX2_XX3_XX4_XX5"

  2. 如果myarray中的3个字符指示符中的任何一个与文件名中的XX2匹配,则在Cell(22,3)上列出XX4,在Cell(22,4)上列出XX5并继续重复......细胞(23,3),细胞(23,4),细胞(24,3),细胞(24,4).....等。我只想要完全匹配..不知道该怎么做。

  3. 文件夹中有一些文件只有3个下划线...所以" XX1_XX2_XX3_XX4"。对于这些文件,如果myarray匹配XX2,则在单元格(i,3)上列出XX4并显示" NO INDICATOR" for Cells(i,4)

  4. 如果我不清楚上述说明的任何部分,请告诉我。 这就是我到目前为止所做的:

    Sub tracker()
    
    Const FPATH As String = "\\KEVINXX\FILESXX\FILES\"
    
    Dim f As String, i, j As Long, arr, sht As Worksheet
    Dim pvt As PivotTable, pvtCache As PivotCache
    Dim myarray As Variant
    myarray = Array("ABC", "XYZ", "YYY", "XXX", "BBB", "CCC", "DDD", "EEE", "FFF", "JJJ")
    Set sht = ActiveSheet
    
    
    f = Dir("\\KEVINXX\FILESXX\FILES\")
    i = 22
    Do While f <> ""
        'split filename on underscore
        arr = Split(f, "_", 5)
        If UBound(arr) = 4 And "*" & myarray(j) & "*" Like arr(1) Then
            sht.Cells(i, 3).Value = arr(3)
            sht.Cells(i, 4).Value = arr(4)
            f = Dir() ' next file
            i = i + 1
        Else
            sht.Cells(i, 3).Value = arr(3)
            sht.Cells(i, 4).Value = "No Indicator"
            f = Dir()
            i = i + 1
        End If
    
    Loop
    

1 个答案:

答案 0 :(得分:0)

未测试:

Sub tracker()

    Const FPATH As String = "\\KEVINXX\FILESXX\FILES\"

    Dim f As String, i, j As Long, arr, sht As Worksheet
    Dim pvt As PivotTable, pvtCache As PivotCache
    Dim myarray As Variant
    myarray = Array("ABC", "XYZ", "YYY", "XXX", "BBB", _
                    "CCC", "DDD", "EEE", "FFF", "JJJ")
    Set sht = ActiveSheet

    f = Dir("\\KEVINXX\FILESXX\FILES\")
    i = 22
    Do While f <> ""

        'split filename on underscore
        arr = Split(f, "_", 5)

        If UBound(arr) >= 3 Then
            If Not IsError(Application.Match(arr(1), myarray, 0)) Then
                sht.Cells(i, 3).Value = arr(3)
                If UBound(arr) >= 4 Then
                    sht.Cells(i, 4).Value = arr(4)
                Else
                    sht.Cells(i, 4).Value = "No indicator"
                End If
                i = i + 1
            End If 'got match
        End If
        f = Dir() 'next file
    Loop
End Sub