VBA编程:workbooks.open打开多个文件

时间:2016-11-14 11:57:22

标签: excel vba excel-vba macros

首先,如果问题太新手,我道歉,因为我自己还在学习VBA。

问题:我在“最终文件夹”中有6个excel文件。我需要依次打开每个,从代码所在的工作簿中输入一些数据(我正在使用这个工作簿作为源代码)。

错误:我尝试了多个选项,但是最新的代码(下面)将所有6个文件一起打开,而不是依次打开它们。

我的观察:在脚本循环中运行workbooks.open时,默认情况下所有文件都会打开。

请帮助。谢谢

Sub PopulateFinalFile()

    Dim filpath As String
    Dim fso As Scripting.FileSystemObject
    Dim fil As Scripting.File
    Dim fldr As Scripting.Folder

    filpath = "C:\Users\deepak.ved\Desktop\Reports\Final Reports"
    Set fso = New Scripting.FileSystemObject
    Set fldr = fso.GetFolder(filpath)

    For Each fil In fldr.Files
        Application.Workbooks.Open (fso.GetFile(fil.Path))
    Next fil


End Sub

无关的问题:如何使用FSO指向工作簿。就像我使用getfilefolder.files一样,它返回一个路径。当我将路径传递给工作簿时,我需要workbook.open(path),但我想要的只是指向该工作簿而不是打开它。

2 个答案:

答案 0 :(得分:0)

试试这个:

Option Explicit

Sub PopulateFinalFile()

    Dim filpath As String
    Dim fso As Scripting.FileSystemObject
    Dim fil As Scripting.File
    Dim fldr As Scripting.Folder

    filpath = "C:\Users\user\Desktop\TEST"
    Set fso = New Scripting.FileSystemObject
    Set fldr = fso.GetFolder(filpath)

    For Each fil In fldr.Files
        Application.Workbooks.Open (fil.Path)
    Next fil


End Sub

它应该逐个开始打开它们。

答案 1 :(得分:0)

已添加到Vityata中,以解决问题的第二部分:

Option Explicit

Sub PopulateFinalFile()

    Dim filpath As String
    Dim fso As Scripting.FileSystemObject
    Dim fil As Scripting.File
    Dim fldr As Scripting.Folder
    Dim wb as workbook

    filpath = "C:\Users\user\Desktop\TEST"
    Set fso = New Scripting.FileSystemObject
    Set fldr = fso.GetFolder(filpath)

    For Each fil In fldr.Files
        set wb = Application.Workbooks.Open(fil.Path)  'no space after open !
        'do some stuff with wb
        wb.close    'close wb
    Next fil


End Sub