在 Excel VBA 中使用 Dir() 访问不止一种类型的文件?
Access more than one type of file with Dir() in Excel VBA?
嘿,我有一个代码,我想在不同的文件夹中找到 .jpg 文件,所以我的代码如下所示:
file = Dir(folder & "\*.jpg")
但事实证明这些文件夹中也有.png 文件,是否有一种简单易行的方法使Dir() 也能找到png 图像?也许以某种方式使用正则表达式,甚至是我没有想到的更简单的方法?我知道有很多方法,但如果我不必更改所有代码,我会喜欢它...感谢任何人回答:)
使用Dir(folder & "\*.*")
列出所有个文件并手动检查它是否是您感兴趣的文件,例如使用这样的函数:
Function isImage(fileName As String) As Boolean
Dim ext As String, p As Long
p = InStrRev(fileName, ".")
If p = 0 Then Exit Function
ext = LCase(Mid(fileName, p + 1))
isImage = (ext = "jpg" Or ext = "jpeg" Or ext = "png")
End Function
请尝试下一种方式:
Dim file as string, folder as string, arrExt
folder = "your folder path"
file = Dir(folder & "\*.*")
Do While file <> ""
arrExt = split(file, ".")
If UCase(arrExt(Ubound(arrExt))) = "JPG" Or _
UCase(arrExt(Ubound(arrExt))) = = "PNG" Then
' do whatever you need
End If
file = Dir
Loop
嘿,我有一个代码,我想在不同的文件夹中找到 .jpg 文件,所以我的代码如下所示:
file = Dir(folder & "\*.jpg")
但事实证明这些文件夹中也有.png 文件,是否有一种简单易行的方法使Dir() 也能找到png 图像?也许以某种方式使用正则表达式,甚至是我没有想到的更简单的方法?我知道有很多方法,但如果我不必更改所有代码,我会喜欢它...感谢任何人回答:)
使用Dir(folder & "\*.*")
列出所有个文件并手动检查它是否是您感兴趣的文件,例如使用这样的函数:
Function isImage(fileName As String) As Boolean
Dim ext As String, p As Long
p = InStrRev(fileName, ".")
If p = 0 Then Exit Function
ext = LCase(Mid(fileName, p + 1))
isImage = (ext = "jpg" Or ext = "jpeg" Or ext = "png")
End Function
请尝试下一种方式:
Dim file as string, folder as string, arrExt
folder = "your folder path"
file = Dir(folder & "\*.*")
Do While file <> ""
arrExt = split(file, ".")
If UCase(arrExt(Ubound(arrExt))) = "JPG" Or _
UCase(arrExt(Ubound(arrExt))) = = "PNG" Then
' do whatever you need
End If
file = Dir
Loop