fixing code merge multiple file into one

abdelfattah

Well-known Member
Joined
May 3, 2019
Messages
1,429
Office Version
  1. 2019
  2. 2010
Platform
  1. Windows
hi,
i have about 3 files and the main file to merge data the code gives me error subscript out of range in this line Set ws = Workbooks("merge file").Worksheets("sheet1")
i'm sure about the name's main file
VBA Code:
Option Explicit

Private Sub CommandButton1_Click()
Dim Path
Dim File
Dim wb As Workbook
Dim x
Dim lr, lr2
Dim ws As Worksheet
Set ws = Workbooks("merge file").Worksheets("sheet1")
Application.ScreenUpdating = False
With ws.Range("a2:r100000"): .ClearContents
.Activate
End With
Path = ThisWorkbook.Path & "\file\"
File = Dir(Path & "*.xlsx*")
    Do While File <> ""
    Set wb = Workbooks.Open(Path & File)
    If Not IsError(x) Then
             lr2 = wb.Worksheets(1).Cells(Rows.Count, "a").End(xlUp).Row
    wb.Worksheets(1).Range("a2:r" & lr2).Copy
    lr = ws.Range("a" & Rows.Count).End(3).Row + 1
    ws.Range("a" & lr).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
     End If
     wb.Close
          File = Dir
     Loop
     Application.ScreenUpdating = True
End Sub
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
Those files are xlsm files, but your code is only opening xlsx files.
 
Upvote 0
so this is no way to adjusting and make it more flexible to open xls,xlsm ...etc
 
Upvote 0
You're welcome & thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,214,885
Messages
6,122,085
Members
449,064
Latest member
MattDRT

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top