排除某些文件类型的VBA语法



我正在尝试创建一个宏,该宏将列出网络文件夹中的所有excel电子表格,但忽略excel在电子表格打开时创建的任何临时文件(即:~$filename.xlsx)。下面的代码工作得很好,但也会拾取这些临时文件。

If (objFile) Like ("*.xlsx") Then
Do something here
End If
Next objFile

我尝试过使用"如果不是"语句,但很难使其发挥作用。我是VBA新手,可能是因为我的语法不正确。有没有办法指定所有.xlsx文件,同时忽略任何临时~$*.xlsx文件?

只需在Like语句中排除以~开头的字符串:

If (objFile) Like ("[!~]*.xlsx") Then
'Do something here
End If

我认为最简单的方法就是在If语句中添加一个额外的子句:

If objFile Like "*.xlsx" And Left(objFile, 2) <> "~$" Then
Do something here
End If
Next objFile

您可以使用Dir执行此操作-请参阅下面的代码:

Public Sub sampleCode()
Dim sourceFolderPath As String
Dim dirStr As String
Dim fileList As Collection
Set fileList = New Collection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select the folder that contains the pictures."
.Show
sourceFolderPath = .SelectedItems(1) & ""
End With
dirStr = Dir(sourceFolderPath & "*.xlsx")
Do Until dirStr = ""
fileList.Add (dirStr)
dirStr = Dir
Loop
End Sub

我将文件名存储在一个集合中,但很明显,您可以将它们存储在数组中或最适合您需要的任何东西中。。

谨致问候,SilkCode

最新更新