2012-11-14 62 views
3

我需要遍歷包含許多excel文件的文件夾並將文件名和創建時間提取到文本文件。通過創建時間,我指的是文件最初創建的時間,而不是在我的系統上創建的時間。獲取文件夾中所有excel文件的原始創建時間

以下代碼有效,但給我錯誤的時間。我認爲FileDateTime是錯誤的命令,但經過一個小時的絕望谷歌搜索後,我一直無法找到正確的命令。

在此先感謝您的幫助!

Sub CheckFileTimes() 
    Dim StrFile As String 
    Dim thisBook As String 
    Dim creationDate As Date 
    Dim outputText As String 
    Const ForReading = 1, ForWriting = 2 
    Dim fso, f 

'set up output file 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set f = fso.OpenTextFile("C:\TEST.txt", ForWriting, True) 

'open folder and loop through 
    StrFile = Dir("c:\HW\*.xls*") 
    Do While Len(StrFile) > 0 
'get creation date 
     creationDate = FileDateTime("C:\HW\" & StrFile) 
'get filename 
     thisBook = StrFile 
     outputText = thisBook & "," & creationDate 
'write to output file 
     f.writeLine outputText 
'move to next file in folder 
     StrFile = Dir 
    Loop 
    f.Close 
End Sub 

回答

1

韋爾普,我找到了答案。看起來我並不太遙遠(雖然我不認爲這是接近最佳的)。感謝所有看過這個的人。

Sub CheckFileTimes3() 
    Dim StrFile, thisBook, outputText As String 
    Dim creationDate As Date 
    Dim fso, f 
    Dim oFS As Object 
    Const ForReading = 1, ForWriting = 2 

    Application.ScreenUpdating = False 
    Application.DisplayAlerts = False 
    Application.EnableEvents = False 

    'open txt file for storing results 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set f = fso.OpenTextFile("C:\TEST.txt", ForWriting, True) 

    'loop through all files in given folder 
    StrFile = Dir("c:\HW\*.xls*") 
    Do While Len(StrFile) > 0 
     Workbooks.Open Filename:="C:\HW\" & StrFile 
     creationDate = ActiveWorkbook.BuiltinDocumentProperties("Creation Date") 
     thisBook = StrFile 
     outputText = thisBook & "," & creationDate 
     'MsgBox outputText 
     f.writeLine outputText 
     ActiveWorkbook.Close 
     StrFile = Dir 
    Loop 
    f.Close 

    Application.ScreenUpdating = True 
    Application.DisplayAlerts = True 
    Application.EnableEvents = True 
End Sub 
1

您可以使用DateCreatedFileSystemObject

一個小調整到當前的代碼做這個

我已擺脫了這些變量以及

Sub CheckFileTimes() 
Dim StrFile As String 
Dim StrCDate As Date 
Dim fso As Object 
Dim f As Object 

'set up output file 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set f = fso.OpentextFile("C:\TEST.txt", 2, True) 

'open folder and loop through 
    StrFile = Dir("c:\HW\*.xls*") 
    Do While Len(StrFile) > 0 
    Set objFile = fso.getfile("c:\HW\" & StrFile) 
'get creation date 
     StrCDate = objFile.datecreated 
'write to output file 
     f.writeLine StrFile & "," & StrCDate 
'move to next file in folder 
     StrFile = Dir 
    Loop 
    f.Close 
End Sub 
+0

感謝您的快速響應。這仍然給我錯誤的時間。 經過一番研究後,它看起來像我需要使用BuiltinDocumentProperties(「創建日期」),但此對象不支持它。 你知道有什麼方法可以應用它嗎? –

+1

實際上'BuiltinDocumentProperties(「創建日期」)'給出了模板創建日期 - 不是工作簿創建日期 – brettdj

+0

有什麼區別? –

相關問題