很好的解决方案亚历克斯。我把你的答案更进一步,稍微偏向一边:)而不是打开所有类似命名的文件。我需要打开最新的,类似命名的文件。所以,我没有这个...
Dim newest As Date
Dim current As Date
Dim right_file As String
Dim rot_cnt As Integer
rot_cnt = 1
Dim my_path As String
Dim file_name As String
my_path = "C:\Path\To\File\Dir\"
file_name = Dir(my_path & "My-Similar-Files*.xlsm")
Do While file_name <> vbNullString
If rot_cnt = 1 Then
newest = FileDateTime(my_path & file_name)
End If
If rot_cnt >= 1 Then
current = FileDateTime(my_path & file_name)
End If
If DateSerial(Year(current), Month(current), Day(current)) >= _
DateSerial(Year(newest), Month(newest), Day(newest)) Then
newest = FileDateTime(my_path & file_name)
right_file = my_path & file_name
End If
file_name = Dir()
rot_cnt = rot_cnt + 1
Loop
Workbooks.Open (right_file), UpdateLinks:=False, ReadOnly:=True
后进一步测试这个使用最后一次保存在“真实”的创作时间,所以它可能会返回不想要的结果。 BuiltinDocumentProperties(“创建日期”)也是创建日期的虚假导向。如果有人复制工作簿,则会克隆此值。为了达到正确的结果而不必手动启用任何新的引用,我使用了这个。
Dim oFS As Object
Dim StrFile As String
Dim rot_cnt As Integer
rot_cnt = 1
Dim current As Date
Dim newest As Date
Dim right_file As String
Dim my_path As String
Dim file_name As String
my_path = "C:\Path\To\File\Dir\"
file_name = "My-Similar-Files*.xlsm"
StrFile = Dir(my_path & file_name)
Do While Len(StrFile) > 0
Set oFS = CreateObject("Scripting.FileSystemObject")
If rot_cnt = 1 Then
newest = oFS.GetFile(my_path & StrFile).DateCreated
End If
If rot_cnt >= 1 Then
current = oFS.GetFile(my_path & StrFile).DateCreated
End If
'The Right(StrFile, 6) If parameter is because Dir() also gives the exact
'string of file_name as one of the values which we don't want to process.
If DateSerial(Year(current), Month(current), Day(current)) >= _
DateSerial(Year(newest), Month(newest), Day(newest)) _
And Right(StrFile, 6) <> "*.xlsm" Then
newest = oFS.GetFile(my_path & StrFile).DateCreated
right_file = my_path & StrFile
End If
StrFile = Dir
Set oFS = Nothing
rot_cnt = rot_cnt + 1
Loop
Workbooks.Open (right_file), UpdateLinks:=False, ReadOnly:=True
我觉得这http://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba 会为你的情况:) – parakmiakos
做查找迪尔函数在VBA帮助中,它将让您查找包含通配符的文件名。例如:“Dashboard * .xls”将选取以“Dashboard”开头的任何xls文件。 –