用于搜索有罪的dat文件并在同一工作簿的单独工作表中打开它们的Vba代码

问题描述 投票:0回答:1

我有一个代码,允许我在excel工作簿中打开多个文件,但是不必手动选择我想要打开的dat文件,我希望能够循环我的代码,以便它遍历我的所有文件并搜索dat文件名为p00001,p00002,p00003等。有谁知道我如何编辑我的代码来选择所谓的这个文件?

我的代码是:

Sub ImportFiles()
    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
excel vba excel-vba openfiledialog worksheet
1个回答
0
投票

你需要做一个文件夹向下钻取。您可以在下面看到示例。你需要做的就是调整这个,如果Statment If InStr(File, ".dat") And InStr(File, "\p0") Then所以只有你想要的文件被打开。

Public sheet As Worksheet
    Public total As Integer
    Public intChoice As Integer
    Public strPath As String
    Public i As Integer
    Public wbNew As Workbook
    Public wbSource As Workbook


Sub main()
Set wbNew = Workbooks.Add
        Dim FileSystem As Object
        Dim HostFolder As String

        HostFolder = "D:\test"

        Set FileSystem = CreateObject("Scripting.FileSystemObject")
        DoFolder FileSystem.GetFolder(HostFolder)
    End Sub

Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files
        If InStr(File, ".dat") And InStr(File, "\p0") Then

            strPath = File
            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
        End If
    Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.