2017-12-19 25 views
0

Excel 파일에서 여러 파일을 열 수있는 코드가 있습니다. 원하는 파일을 수동으로 선택하지 않아도됩니다. open 내 코드를 반복하여 p00001, p00002, p00003 등의 모든 dat 파일을 검색합니다. 누구든지 내 코드를 편집하여이 모든 파일을 선택하는 방법을 알고 있습니까?VBA 코드를 사용하여 dat 파일을 무의미하게 검색하여 동일한 통합 문서의 별도 시트에서 열 수 있음

내 코드는 다음과 같습니다 당신은 폴더를 드릴 다운 할 필요가

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

컴퓨터의 * 모든 곳 *에 있습니까? 또는 열거 나 사용하려는 모든 파일을 포함하는 폴더 (하위 폴더 포함)가 있습니까? – BruceWayne

+0

그들은 모두 큰 폴더 내의 다른 하위 폴더에 모두 포함되어 있습니다. –

+0

하위 폴더에서 파일을 반복하는 방법을 찾은 다음 파일 이름과 함께 If 문을 사용할 수 있습니다 (예 : If Instr (1, myFile.Name , "P00") 그런 다음 .... – BruceWayne

답변

0

. 아래 샘플을 볼 수 있습니다. Statement 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 
+0

고맙지 만 코드가 strPath 코드 줄에서 버그를 찾아내는 이유는 무엇입니까? –

+0

@ J.Smith 코드에서 왼쪽이있었습니다. 이제는 작동해야합니다 – Moosli

+0

나는 여전히 작동하지 않습니다, 그것을 통해 반복 루프를 통해 파일을 선택하면 그냥 파일 열기 대화 상자를 보여줍니다 @ Moosli –