如何指向目录以在vba的每个文件上启动workbooks.opentext命令

时间:2016-12-12 01:20:01

标签: excel vba excel-vba

在VBA中,我有一个Workbooks.OpenText命令:

Workbooks.OpenText Filename:=strFileToOpen, StartRow:=11, DataType:=xlDelimited, Tab:=True, TrailingMinusNumber:=True

但是,不是逐个文件打开并将其添加到我的工作簿中。我想将其指向一个目录,并让VBA(Excel)为目录中的每个文件执行Workbooks.OpenText函数。我该怎么做?

1 个答案:

答案 0 :(得分:1)

欢迎来到论坛! 您可以列出文件夹中的文件,并使用下面的示例代码打开它们。只需更改目录和模式识别器即可。它目前设置为在C:\ temp \文件夹中搜索.xlsm文件

Public Sub OpenFilesInFolder()
    Const folder_to_search As String = "C:\temp\"
    Const pattern_recognition As String = "*.xlsm"
    Dim the_file_name As String
    Dim full_path As String
    'the_file_name = Dir(folder_to_search & pattern_recognition, vbNormal)  'Applies the pattern recognition
    the_file_name = Dir(folder_to_search, vbNormal)                        'Does not apply the pattern recognition
    Do While Len(the_file_name) > 0
        full_path = folder_to_search & the_file_name
        Debug.Print full_path 'The full path will be printed in the Immediate window Ctrl+G will open this
        Workbooks.OpenText Filename:=full_path
        the_file_name = Dir 'Move onto the next file
    Loop
End Sub