VBA按顺序导入文件

时间:2016-09-09 14:41:13

标签: excel-vba vba excel

我有以下代码从特定目录中获取docx文件。然后另一部分代码将表中的表解析为excel文件。我的问题是文件没有按顺序处理。它们被随机抓取。为了让我的最终文件具有正确的数据,我需要按顺序处理(所有文件都以1,2,3..etc开头)

Dim MyFile As Variant
Dim Counter As Long

'Create a dynamic array variable, and then declare its initial size
Dim DirectoryListArray() As String
ReDim DirectoryListArray(1000)

'Loop through all the files in the directory by using Dir$ function
MyFile = Dir$("c:\test\output\*.*")
Do While MyFile <> ""
DirectoryListArray(Counter) = MyFile
MyFile = Dir$
Counter = Counter + 1
Loop

'Reset the size of the array without losing its values by using Redim Preserve
ReDim Preserve DirectoryListArray(Counter - 1)


Dim Loc As String
Loc = "C:\test\output\"

2 个答案:

答案 0 :(得分:0)

我找到另一个线索给我一个答案。我不得不使用其他一些东西。 此Quicksort Algorithm和此function从文件夹中获取文件。在这些帮助下,我做了以下更改。

Dim allFiles As Variant
Dim Mydir As String
Mydir = "c:\builds\combine\"
allFiles = GetFileList(Mydir & "*.docx")
If IsArray(allFiles) Then
Call QuickSort(allFiles, LBound(allFiles), UBound(allFiles))
End If

然后在下面的代码中处理表,我只是将它指向allFiles数组并按顺序加载它。

答案 1 :(得分:-1)

注意:我确实说我没有测试过。我在VBA工作了一段时间。对不起:

好的 - 似乎并不是一个干净的&#39;方便使用Dir $排序,所以我可能会用shell滚动。

Shell(&#34; cmd.exe / C目录c:\ test *。* / a:-d / o:n / b&gt; c:\ test \ output \ myfiles.txt&#34;)< / p>

然后使用fso读取myfiles.txt,它将按名称升序排序。 / a:-d就在那里,所以列表不包含目录,而/ b只给你裸文件名(没有大小和日期信息)。

这个问题可能是 - 在使用alpha排序时你必须注意数字 - 因为1到199999将在2之前排序。