【问题标题】:Wildcard Array in If Statement in VBAVBA中If语句中的通配符数组
【发布时间】:2018-03-10 19:44:16
【问题描述】:

我想用这段代码做的是:

  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 匹配,则在 Cells(i,3) 上列出 XX4 并为 Cells(i,4) 显示“NO INDICATOR”

如果我对上述描述的任何部分不清楚,请告诉我。 这是我目前所拥有的:

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

【问题讨论】:

  • sht.Cells(i, 3).Value = arr(3)f = Dir()i = i + 1 放在end if 之后......从if 语句中删除它们......你的if 语句只影响sht.Cells(i, 4)的值

标签: arrays excel vba wildcard


【解决方案1】:

未经测试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多