首页 > 解决方案 > 如何指定顺序 Dir() 查看 vba 中的文件

问题描述

我正在使用 excel vba 中的 Dir() 函数对文件夹中的文件进行排序并对每个文件执行一些转换。Dir() 默认情况下按文件名的字母顺序浏览文件。我希望能够指定 Dir() 函数通过文件的顺序。具体来说,我希望它按修改日期的顺序遍历文件。

宏遍历用户指定的文件夹,在 excel 中打开文件夹中的 .txt 文件,格式化数据,计算数据的统计数据(平均值、标准差等),然后将这些统计数据复制到另一个 excel 文件中。我发现这个问题按字母顺序对文件进行排序,但我需要按修改日期对它们进行排序。我已经复制了下面代码的相关部分。我不知道如何让语法突出显示工作,所以如果难以理解,我提前道歉。

Sub MahloDataToText()

     Dim folder_to_search As String
     Dim full_path As String
     Dim the_file_name As String

     folder_to_search = ActiveSheet.Cells(4, "D").Value
     Const pattern_recognition As String = "*.txt"
     the_file_name = Dir(folder_to_search & pattern_recognition, vbNormal)

     Do While Len(the_file_name) > 0

          full_path = folder_to_search & the_file_name

          Workbooks.OpenText Filename:=full_path, Origin:=437, StartRow:=5, DataType:=xlDelimited, TextQualifier:= _
                        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, _
                        Comma:=False, Space:=False, Other:=False

          'here is where all the formatting, statistics, and copying take place. Excluded for space'

          the_file_name = Dir
     Loop

End Sub

基本上问题在于 Dir() 函数打开文件的顺序。它按字母顺序打开它们,我需要按修改日期的顺序打开它们。我已经尝试按照我想要的方式手动对文件夹进行提前排序,但这似乎不会影响 Dir() 函数。

如果有办法让我指定打开文件的顺序,那么这将解决问题。

标签: excelvbasortingdirectory

解决方案


推荐阅读