2016-12-12 36 views
1

在VBA啓動workbooks.opentext命令,我有一個Workbooks.OpenText命令:如何指向目錄中的每個文件的VBA

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

然而,不是開放逐文件並將其添加到我的工作簿。我想將其指向一個目錄,並使VBA(Excel)爲目錄中的每個文件執行Workbooks.OpenText功能。我怎麼做?

+1

您可以使用此作爲起點http://stackoverflow.com/questions/10380312/loop-through-files-in -a-folder-using-vba – nightcrawler23

回答

1

歡迎來到論壇! 您可以列出文件夾中的文件並使用下面的示例代碼打開它們。只需更改目錄和模式識別器即可。它當前設置爲搜索.XLSM文件在C:\ TEMP \文件夾

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 
+1

'pattern_recognition' should probably ='「* .csv」'但我知道你沒有使用它。我會把'Workbooks.OpenText'作爲循環中的第二行跟隨'full_path',以將邏輯保持在一起。但很好的工作 –

+0

@ThomasInzina好點..交換了OpenText行 –

+0

看起來不錯... :) –

相關問題