VBA代码:打开多个文件并在同一工作簿的不同工作表中显示

3
我有一个代码可以打开Excel工作簿中的一个文件,但是我想要能够在同一个名为p00001、p00002、p00003等的工作簿中打开多个文件。有谁知道如何编辑我的代码以选择所有以这种方式命名的文件,并在同一工作簿的不同工作表中打开它们吗?
我的代码如下:
Sub Open_Workbook()

    Dim my_FileName As Variant

    my_FileName = Application.GetOpenFilename

    If my_FileName <> False Then
        Workbooks.Open Filename:=my_FileName
    End If

End Sub

这是什么类型的文件? - Moosli
你可以循环遍历文件夹中的所有Excel文件,并执行想要的操作,这样可行吗? - Lowpar
这些文件是dat文件,是的,我希望能够以某种方式进行循环。 - user9103716
1个回答

4

在此解决方案中,我使用了FileDialog来选择多个文件。 之后,您需要循环遍历所有这些文件。 在For Loop内部,您必须打开文件并导入工作表。在本示例中,我导入了Workbook中的所有Sheet。 代码导入完成后,关闭源工作簿,然后对其余文件执行相同操作。

Sub Import Files()
        Dim sheet As Worksheet
        Dim total As Integer
        Dim intChoice As Integer
        Dim strPath As String
        Dim i As Integer
        Dim wbNew As Workbook
        Dim wbSource As Workbook
        Set wbNew = Workbooks.Add


        'allow the user to select multiple files
        Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = True
        'make the file dialog visible to the user
        intChoice = Application.FileDialog(msoFileDialogOpen).Show

        Application.ScreenUpdating = False
        Application.DisplayAlerts = False

        'determine what choice the user made
        If intChoice <> 0 Then
            'get the file path selected by the user
            For i = 1 To Application.FileDialog(msoFileDialogOpen).SelectedItems.Count
                strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(i)

                Set wbSource = Workbooks.Open(strPath)

                For Each sheet In wbSource.Worksheets
                    total = wbNew.Worksheets.Count
                    wbSource.Worksheets(sheet.Name).Copy _
                    after:=wbNew.Worksheets(total)
                Next sheet

                wbSource.Close
            Next i
        End If

    End Sub

如果您想从一个目录中获取所有文件,可以使用循环来遍历该目录,例如将ApplicationFileDialog更改为以下形式的循环:
 directory = "c:\test\"
    fileName = Dir(directory & "*.xl??")
    Do While fileName <> ""
    'Put Code From For Loop here.
    Loop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接