Use VBA to merge multiple Excel workbooks

Source: Internet
Author: User

There are many ways to merge Excel workbooks. Examples of combining workbooks are described in "merging data from multiple workbooks into one Workbook. The following examples are provided for your reference.

For example, you need to merge worksheets from multiple Excel workbooks into one workbook. Assume that the workbook to be merged contains two worksheets in "D:/example/data record/Workbook". Now, use a piece of VBA code to merge the two workbooks into a new workbook, the worksheet that is merged into the new Workbook is named after the original workbook name and the index value. The Code is as follows:

Sub combineworkbooks ()
Dim strfilename as string
Dim WB as workbook
Dim ws as object
 
'Folder containing the workbook, which can be modified as needed
Const strfiledir as string = "D:/example/data record /"
 
Application. screenupdating = false
 
Set WB = workbooks. Add (xlworksheet)
Strfilename = Dir (strfiledir & "*. xls *")
 
Do While strfilename <> vbnullstring
Dim wborig as workbook
Set wborig = workbooks. Open (filename: = strfiledir & strfilename, readonly: = true)
Strfilename = left (strfilename, Len (strfilename)-4), 29)
 
For each ws in wborig. Sheets
WS. Copy after: = WB. Sheets (WB. Sheets. Count)
If wborig. Sheets. Count> 1 then
WB. Sheets (WB. Sheets. Count). Name = strfilename & ws. Index
Else
WB. Sheets (WB. Sheets. Count). Name = strfilename
End if
Next
 
Wborig. Close savechanges: = false
 
Strfilename = dir
 
Loop
 
Application. displayalerts = false
WB. Sheets (1). Delete
Application. displayalerts = true
 
Application. screenupdating = true
 
Set WB = nothing
 
End sub

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.