Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA按顺序导入文件_Excel_Vba - Fatal编程技术网

Excel VBA按顺序导入文件

Excel VBA按顺序导入文件,excel,vba,Excel,Vba,我有以下代码从特定目录中获取docx文件。然后,另一段代码将表格解析为excel文件。我的问题是文件没有按顺序处理。他们被随机抓走。为了使我的最终文件具有正确的数据,我需要对其进行处理,以便所有文件以1,2,3..等开头 Dim MyFile As Variant Dim Counter As Long 'Create a dynamic array variable, and then declare its initial size Dim DirectoryListArray() As

我有以下代码从特定目录中获取docx文件。然后,另一段代码将表格解析为excel文件。我的问题是文件没有按顺序处理。他们被随机抓走。为了使我的最终文件具有正确的数据,我需要对其进行处理,以便所有文件以1,2,3..等开头

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\"

注意:我说过我没有测试过。我已经有一段时间没有在VBA内部工作了。对不起:

好的-似乎没有一种“干净”的方法可以使用Dir$轻松排序,所以我可能会使用shell

Shell cmd.exe/C dir C:\test*/a:-d/o:n/b>C:\test\output\myfiles.txt

然后使用fso读取myfiles.txt,它将按名称升序进行良好排序。a:-d在那里,所以列表中不包含目录,/b只提供裸文件名,没有大小和日期信息

这样做的一个问题可能是——在使用alpha排序时,您必须注意数字——因为1到199999将在2之前排序


我找到了另一条线索,为我指明了答案。我不得不用其他几件。 这个和这个从文件夹中获取文件。在这些帮助下,我做了以下更改

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数组,并按顺序加载它

一种方法是对文件名数组进行排序。我知道如何调用该数组,我将使用此调用QuickSortmyArray,0,UBoundmyArray如何将其输入到我的代码中?将Dir$?Dir$默认值替换为文件名排序顺序。如果位数不匹配,文件名是否有前导零?例如,1_foo.docx、10_foo.docx、2_foo.docx。我给它们添加了数字以保持它们的独立性,有一些ABC文件,但它们的结尾不同。名称都不同,因此顺序将保持数字,因此10永远不会出现在2之前。它们都是1ABC_name_version,2DEF_difname_version如果我加上处理单词doc的代码部分,它告诉我由于某种原因我的文档没有表?Dir$不支持shell命令行参数。如果执行它,并且alpha是默认排序,则这是一个运行时错误。