2017-12-18 108 views
3

我有一個代碼,允許我在Excel工作簿中打開文件,但是我希望能夠在同一個工作簿中打開多個文件,名爲p00001,p00002 ,p00003等。有誰知道我可以如何編輯我的代碼來選擇所有以這種方式命名的文件,並在同一工作簿的不同工作表中打開它們?Vba代碼在同一工作簿的單獨工作表中打開多個文件

我的代碼是:

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

什麼類型的文件有那些? – Moosli

+0

你可以遍歷一個文件夾中的所有Excel文件並做你想做的事,這會工作嗎? – Lowpar

+0

這些文件是dat文件,是的,我想能夠以某種方式循環 –

回答

3

在這個解決方案,我用的FileDialog用於選擇多個文件。 之後,你需要循環所有thoes文件一個循環。 在For循環中,您必須打開文件並導入工作表。在本例中,我導入了工作簿所有的表格。 代碼完成導入後關閉源工作簿並對其餘文件執行相同操作。

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 

如果你想獲得所有文件,您可以更改ApplicationFile對話與循環目錄是你循環目錄是這樣的:

directory = "c:\test\" 
    fileName = Dir(directory & "*.xl??") 
    Do While fileName <> "" 
    'Put Code From For Loop here. 
    Loop 
相關問題