2010-01-13 62 views
0

我想嘗試一些東西,我確信這是可能的,但不是真正肯定從excel中讀取文件夾和任何文檔屬性?

在MS Excel(2003年),我可以寫一個腳本,VBA,這將打開一個位置(例如:S://公共/營銷/文件/),並列出位於那裏(文件名)內的所有文件?

的最終目標將是有文件名,最後修改日期,創建和名稱修改日期。

這可能嗎?我想返回表單中行中找到的任何值。例如:類型:文件夾,鍵入:Word文檔等

感謝您的信息!

回答

1

最近做了。使用DSOFile對象。在Excel-VBA中,首先需要創建對Dsofile.dll(「DSO OLE文檔屬性閱讀器2.1」或類似文檔)的引用。另外,請檢查你的辦公室圖書館

首先引用您可能要選擇要檢查的文件路徑

Sub MainGetProps() 
Dim MyPath As String 

    MyPath = GetDirectoryDialog() 
    If MyPath = "" Then Exit Sub 

    GetFileProps MyPath, "*.*" 
End Sub 

讓我們有一個很好的路徑選擇窗口

Function GetDirectoryDialog() As String 
Dim MyFD As FileDialog 

    Set MyFD = Application.FileDialog(msoFileDialogFolderPicker) 
    With MyFD 
     .AllowMultiSelect = False 
     .Show 
     If .SelectedItems.Count <> 0 Then 
      GetDirectoryDialog = .SelectedItems(1) 
     End If 
    End With 

End Function 

現在讓我們使用DSO對象讀出信息...我將代碼縮減爲必要的代碼

Private Sub GetFileProps(MyPath As String, Arg As String) 
Dim Idx As Integer, Jdx As Integer, MyFSO As FileSearch, MyRange As Range, MyRow As Integer 
Dim DSOProp As DSOFile.OleDocumentProperties 

    Set DSOProp = New DSOFile.OleDocumentProperties 
    Set MyRange = ActiveSheet.[A2] ' your output is nailed here and overwrites anything 

    Set MyFSO = Application.FileSearch 

    With MyFSO 
     .NewSearch 
     .LookIn = MyPath 
     .SearchSubFolders = True ' or false as you like 
     .Filename = Arg 
     .FileType = msoFileTypeAllFiles 
     If .Execute() > 0 Then 
      MsgBox .FoundFiles.Count & " file(s) found." ' to see what you will get 
      For Idx = 1 To .FoundFiles.Count 

       DSOProp.Open .FoundFiles(Idx) ' examine the DSOProp element in debugger to find all summary property names; not all may be filled though 
       Debug.Print .FoundFiles(Idx) 
       Debug.Print "Title: "; DSOProp.SummaryProperties.Title 
       Debug.Print "Subject: "; DSOProp.SummaryProperties.Subject 
       ' etc. etc. write it into MyRange(Idx,...) whatever 

       ' now hunt down the custom properties 
       For Jdx = 0 To DSOProp.CustomProperties.Count - 1 
        Debug.Print "Custom #"; Jdx; " "; 
        Debug.Print " Name="; DSOProp.CustomProperties(Jdx).Name; 
        If DSOProp.CustomProperties(Jdx).Type <> dsoPropertyTypeUnknown Then 
         Debug.Print " Value="; DSOProp.CustomProperties(Jdx).Value 
        Else 
         Debug.Print " Type=unknowwn; don't know how to print"; 
        End If 
        MyRow = MyRow + 1 
       Next Jdx 
       DSOProp.Close 
      Next Idx 
     Else 
      MsgBox "There were no files found." 
     End If 
    End With 
End Sub 

那就應該是吧

祝你好運MikeD

+0

太棒了!今天我會告訴你一切,讓你知道它是怎麼回事! – 2010-01-14 10:27:17

+0

我已經複製了代碼,因爲你把它和一旦我確認文件夾來查看,它只是崩潰的Excel!我認爲它陷入了一些循環。我會試圖找出什麼.... – 2010-01-14 13:27:15

+0

哎呀!在發佈之前,我通過我的調試器運行了這個程序。我有XP的Excel 2003 SP2和我引用的MSOffice 11.0對象庫,DSO OLE和MS除了默認 – MikeD 2010-01-14 14:12:00