我想找出一種方法來打開所有子文件夾中的所有Excel文件,並獲取第1行中所有單元格的所有值以及所有這些單元格的所有格式。我認爲我的代碼非常接近,但我認爲其中一個引用是不正確的,或類似的東西。無論如何,當我運行代碼時,它會打開第一個Excel文件,大約一秒鐘後,一切都會凍結。如何遍歷所有子文件夾並獲取每個Excel文件的第1行的內容?
Sub GetFolder_Data_Collection()
Range("A:L").ClearContents
Range("A1").Value = "Name"
Range("B1").Value = "Path"
Dim strPath As String
strPath = GetFolder
Dim OBJ As Object, Folder As Object, File As Object
Set OBJ = CreateObject("Scripting.FileSystemObject")
Set Folder = OBJ.GetFolder(strPath)
Call ListFiles(Folder)
Dim SubFolder As Object
For Each SubFolder In Folder.SubFolders
Call ListFiles(SubFolder)
Call GetSubFolders(SubFolder)
Next SubFolder
End Sub
Sub ListFiles(ByRef Folder As Object)
Dim sht As Worksheet
Dim LastRow As Long
Dim cCount As Long
Dim lngColCount As Long
Set sht = ThisWorkbook.Worksheets("Sheet1")
On Error Resume Next
For Each File In Folder.Files
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row + 1
Set wbSource = Workbooks.Open(Filename:=File)
Set wsSource = wbSource.Worksheets(1)
'lngRowCount = wsSource.UsedRange.Rows.Count
lngColCount = wsSource.UsedRange.Columns.Count
For cCount = 1 To lngColCount
Range("A" & LastRow).Select
ActiveCell = File.Name
ActiveCell.Offset(0, 1).Value = File.Path
ActiveCell.Offset(0, 2).Hyperlinks.Add Anchor:=ActiveCell.Offset(0, 0), Address:=File.Path, TextToDisplay:=File.Path
ActiveCell.Offset(0, 3).Value = File.Worksheets(1).Range(1, lngColCount).Value
ActiveCell.Offset(0, 4).Value = File.Worksheets(1).Range(1, lngColCount).Format
Next cCount
Next File
End Sub
Sub GetSubFolders(ByRef SubFolder As Object)
Dim FolderItem As Object
On Error Resume Next
For Each FolderItem In SubFolder.SubFolders
Call ListFiles(FolderItem)
Call GetSubFolders(FolderItem)
Next FolderItem
End Sub
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
再一次,我想獲得第一行(每個Excel文件)的所有單元格值和這些單元格中的每一個的所有格式。
請幫忙。 謝謝!
當你用'F8'過關時,你可能會陷入某個循環嗎? – BruceWayne
註釋掉你的錯誤繼續下一步 - 你會得到錯誤嗎? –
(a)'File'不是'Workbook'對象,所以不會有'Worksheets'屬性。該錯誤正被「On Error Resume Next」屏蔽。你應該只在你知道**你掩蓋什麼錯誤時才使用該語句。 (b)您的代碼正在更新活動工作表中的值,該工作表位於您打開的工作簿中 - 您不打算更新'sht'中的內容。 (c)你的代碼對我來說「工作」(即它沒有鎖定 - 我不是說它有意義),但是我使用了一個只有大約6個工作簿的目錄。我懷疑你的「凍結」只是打開太多的工作簿。 – YowE3K