我有一个包含一些excel文件的文件夹。
在每个文件中,我想创建一个包含“数据”表中数据的数组。每个工作簿或文件都有此工作表。
唯一的问题是文件夹中每次都可能有不同数量的文件。
我想捕获每个数组中每个文件的“数据”工作表的内容,然后将所有这些数据写入一个文件。
问题 是否可以根据例如文件夹中的文件数动态创建数组?
如果是这样,你如何创建这些动态数组?
示例 而不是有一个数组(我改变了大小)我想... (取决于文件夹中的文件数量,例如创建多个单独的数组?
e.g。文件夹中的3个文件
dim array01 昏暗的阵列02 昏暗的阵列
在文件夹中为每个工作簿创建一个数组是更好的 - 存储“数据”工作表的内容,还是创建一个更大的数组?
答案 0 :(得分:1)
不要使用多维数组并一直重新编写它,而是考虑将每个数据数组存储在Collection
中,如下所示:
Dim allData As Collection, data As Variant, file As Variant
Dim wb As Workbook, ws As Worksheet
Set allData = New Collection
file = Dir("c:\testfolder\*.xlsx")
While (file <> "")
Set wb = Workbooks.Open(file)
data = wb.Sheets(1).UsedRange.Cells 'Adjust this to get your data range
allData.Add data, file
file = Dir
Wend
稍后您可以使用For Each
循环来检索数据:
Dim count As Integer
For Each data In allData
count = count + 1
Debug.Print "Dataset #" & count & " has " & _
UBound(data, 1) & " x " & UBound(data, 2) & " entries"
Next
答案 1 :(得分:0)
Sub MAIN()
Dim FolderOfInterest As String, i As Long
FolderOfInterest = "C:\TestFolder"
Dim ary()
ary = files_in_folder(FolderOfInterest)
MsgBox "There are " & UBound(ary) & " files in folder " & FolderOfInterest
'
' Now store the array in a worksheet column
'
i = 1
For Each a In ary
Cells(i, "A").Value = a
i = i + 1
Next a
End Sub
Public Function files_in_folder(folderS As String) As Variant
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderS)
ReDim temp(1 To folder.Files.Count)
i = 1
For Each file In folder.Files
temp(i) = file.Name
i = i + 1
Next file
files_in_folder = temp
End Function