楊老師課堂_VBA學習教程之一鍵合並所有文件


 

文件合並示例代碼:

  要求:在C盤中有一個文件夾,文件夾中有文件存在

Sub wjhb()
Dim str As String
Dim wb As Workbook

 
 str = Dir("c:\data\*.*")
 
    For i = 1 To 20
       ' 1 打開文件
     Set wb = Workbooks.Open("c:\data\" & str & "")
          ' 2 從遍歷中的某一個工作簿中的第一張表執行拷貝 到這個工作簿中的最后一張表中去
       wb.Sheets(1).Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
          ' 3 在這個工作簿中的最后一張表的名字是【已經完成拷貝操作】  = 文件名稱
       ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = Split(str, ".")(0)
          '4 遍歷中的工作簿執行關閉
       wb.Close
           '下一次遍歷
       str = Dir
       
       If str = "" Then
            Exit For
       End If
        
    Next

End Sub

 

End Sub
Sub wjhb2()
Dim str As String
Dim wb As Workbook

 
 str = Dir("c:\data\*.xlsx")
 
    For i = 1 To 20
       
     Set wb = Workbooks.Open("c:\data\" & str & "")
        
       wb.Sheets(1).Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
       ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = str
       wb.Close
       str = Dir
       
       If str = "" Then
            Exit For
       End If
        
    Next
End Sub

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM