Stackbros
我有一些VBA用于将.csv文件从指定文件夹导入Excel。导入后,脚本会执行一些其他转换,例如分隔和偏移。见下文。
Sub OpenTextFile ()
Dim FilePath As String
FilePath = "C:\Foldername\Foldername\Foldername\File_name.CSV"
Open FIlePath For Input As #1
row_number = 0
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems = Split(LineFromFile, ",")
ActiveCell.Offset (row_number, 0).Value = LineItems (2)
ActiveCell.Offset (row_number, 1).value = LineItems (1)
ActiveCell.Offset (row_number, 2).Value = LineItems (0)
row_number = row_number + 1
Loop
Close #1
End Sub
我真正想要做的就是修改它,这样当我运行它时,我总是根据文件夹中文件的日期属性从文件夹中导入最新文件。
提前致谢。
答案 0 :(得分:2)
看看这个例程。这是相当古老但我认为它做你想要的。如果没有,它应该给你一些想法。
Function NewestFileName(ByVal Path As String, ByVal FileTemplate As String) As String
' * Path Folder in which to search for files
' * FileTemplate File name specification of the file required. For example:
' MyFile*.xls
' * Finds, and returns the name of, the newest file in folder Path with a name
' that matches FileTemplate. Returns "" if no matching file is found.
' 25Jul11 Copied from RiskRegisterControl V43.xls.
' 22Nov11 Name changed from NewestFile to NewestFileName to match NextFileName.
' 20Apr12 Minor improvements
Dim FileDateCrnt As Date
Dim FileDateNewest As Date
Dim FileNameCrnt As String
Dim FileNameNewest As String
If Right(Path, 1) <> "\" Then
Path = Path & "\"
End If
FileNameCrnt = Dir$(Path & FileTemplate)
If FileNameCrnt = "" Then
NewestFileName = ""
Exit Function
End If
FileNameNewest = FileNameCrnt
FileDateNewest = FileDateTime(Path & FileNameCrnt)
Do While True
FileNameCrnt = Dir$
If FileNameCrnt = "" Then Exit Do
FileDateCrnt = FileDateTime(Path & FileNameCrnt)
If FileDateCrnt > FileDateNewest Then
FileNameNewest = FileNameCrnt
FileDateNewest = FileDateCrnt
End If
Loop
NewestFileName = FileNameNewest
End Function