Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VBScript

Merge Excel Files into One Using VB Script

5.00/5 (1 vote)
24 Jun 2020CPOL 26K   152  
How to merge multiple Excel files into one with the help of VB script
In this tip, you will see a script that uses VBA to import worksheets from each file on one workbook to merge Excel files into one Excel file.

Introduction

Merge Excel files into one on Excel file. The script is using VBA to import worksheets from each file into one workbook. Add file to be merged to MergeExcel.txt and double click MergeExcel.vbs to run it.

Using the Code

MergeExcel.txt - contains the list of files to be merged. Open Windows Explorer hold shift and right click on the Excel file. Select "Copy as path" and copy the Excel file path to MergeExcel.txt (each line per file path).

MergeExcel.vbs - VB Script file. Double click to run it. The script will read MergeExcel.txt located in the same folder.

MergeExcel.vbs source code:

VBScript
Set fso = CreateObject("Scripting.FileSystemObject")
sFolderPath = GetFolderPath()
sFilePath = sFolderPath & "\MergeExcel.txt"

If fso.FileExists(sFilePath) = False Then
  MsgBox "Could not file configuration file: " & sFilePath
  WScript.Quit
End If

Dim oExcel: Set oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oExcel.DisplayAlerts = false
Set oMasterWorkbook = oExcel.Workbooks.Add()
Set oMasterSheet = oMasterWorkbook.Worksheets("Sheet1")
oMasterSheet.Name = "temp_delete"
oMasterWorkbook.Worksheets("Sheet2").Delete
oMasterWorkbook.Worksheets("Sheet3").Delete

Set oFile = fso.OpenTextFile(sFilePath, 1)   
Do until oFile.AtEndOfStream
  sFilePath = Replace(oFile.ReadLine,"""","")
  
  If fso.FileExists(sFilePath) Then
    Set oWorkBook = oExcel.Workbooks.Open(sFilePath)
    
    For Each oSheet in oWorkBook.Worksheets
      oSheet.Copy oMasterSheet
      'oSht.Move , oSheet
    Next
    
    oWorkBook.Close()
  End If
Loop
oFile.Close

oMasterSheet.Delete
MsgBox "Done"
          
Function GetFolderPath()
    Dim oFile 'As Scripting.File
    Set oFile = fso.GetFile(WScript.ScriptFullName)
    GetFolderPath = oFile.ParentFolder
End Function

History

  • 24th June, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)