VBA to make filepath dynamic

Gorandulac32

New Member
Joined
Jan 9, 2020
Messages
18
Office Version
  1. 2016
Platform
  1. Windows
So the below code works to go into a file path C:\Users\Goran\2021\06 and takes all the files from that file path and combines them into 1 file and the contents of each file are a separate tab. For example 0601file, 0602file from the folder get created as a tab on the master file. The question is how do i dynamically account for the month change. The code I have below works, but i would need to change the date manually each time and then run the macro.



Sub MergeWorkbooks()

Dim FolderPath As String
Dim File As String
Dim i As Long


FolderPath = "C:\Users\Goran\2021\06

File = Dir(FolderPath)

Do While File <> ""

Workbooks.Open FolderPath & File
ActiveWorkbook.Worksheets(1).Copy _
after:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
ActiveSheet.Name = Replace(File, ".xlsx", "")
Workbooks(File).Close

File = Dir()

Loop

For i = 1 To 12

Worksheets(MonthName(i, True)).Move after:=Worksheets(Worksheets.Count)

Next


End Sub
 

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
How about
VBA Code:
FolderPath = "C:\Users\Goran\" & year(date) & "\" & format(date,"mm")
 
Upvote 0
I get an error on Worksheets(MonthName(i, True)).Move after:=Worksheets(Worksheets.Count)

run-time error ’9’
 
Upvote 0
Yes it works in my original code but it doesn’t work in the dynamic formula adjusted one you suggested. I guess what code would I need to go to a folder and pull each file and create a master file with each file as a separate tab.

thanks
 
Upvote 0
That has nothing to do with your original question, so you need to start a new thread for that question. Thanks
 
Upvote 0

Forum statistics

Threads
1,214,940
Messages
6,122,361
Members
449,080
Latest member
Armadillos

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