您可以在VBA Dir函数中使用多个通配符吗?

时间:2018-08-29 10:09:11

标签: vba excel-vba directory wildcard

我正在处理一个宏以输出文件名。我有一个目录,其中包含工业批处理过程的日志文件。每个批次分配一个5位数字的批次号,每个批次都有一个.csv和.txt文件。这两个文件的文件名相同,并包含批处理号,例如:

XYZ 53482 20180827.csv
XYZ 53482 20180827.txt
XYZ 53483 20180828.csv
XYZ 53483 20180828.txt
XYZ 53484 20180829.csv
XYZ 53484 20180829.txt

到目前为止,我的宏是:

Sub FindBatchFile()
Dim Batch As Double
Dim DirPath As String, r As Integer

Batch = InputBox("Enter Batch Number")

DirPath = Dir("C:\Data\* " & Batch & "*", vbDirectory)
r = 1
Workbooks.Add
MsgBox (DirPath)

Do Until DirPath = ""
Cells(r, 1).Value = DirPath
MsgBox (DirPath)
r = r + 1
DirPath = Dir
Loop

End Sub

这可以正常工作,但是输出同时包含.csv和.txt文件。在Dir函数中是否可以使用多个通配符(即,包括“ *.csv”条件以及“ *Batch*”)?

非常感谢!

1 个答案:

答案 0 :(得分:1)

我相信,只要在您的DirPath中添加.csv,以下内容就会按您期望的那样工作:

Sub FindBatchFile()
Dim Batch As Double
Dim DirPath As String, r As Integer

Batch = InputBox("Enter Batch Number")

DirPath = Dir("C:\Data\* " & Batch & "*.csv", vbDirectory)
r = 1
Workbooks.Add
MsgBox (DirPath)

Do Until DirPath = ""
    Cells(r, 1).Value = DirPath
    MsgBox (DirPath)
    r = r + 1
    DirPath = Dir
Loop

End Sub