【问题标题】:Can you use multiple wildcards in the VBA Dir function?您可以在 VBA Dir 函数中使用多个通配符吗?
【发布时间】:2019-02-04 02:09:44
【问题描述】:

我正在开发一个宏来输出文件名。我有一个包含工业批处理日志文件的目录。每个批次都分配有一个 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*”)?

非常感谢!

【问题讨论】:

  • DirPath = Dir("C:\Data\* " & Batch & "*.csv", vbDirectory) 怎么样?

标签: vba excel directory wildcard


【解决方案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

【讨论】:

  • 非常感谢 Xabier!如此简单的解决方案,但效果很好。感谢您抽出宝贵时间回复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-28
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多