I am attempting to make a loop VBA macro to:
- Open first file in folder called
New
- Copy data row in
Defined Name
cell rangeexport_data
- Paste it into my current workbook on a new row at
A1
onSheet1
- Close without saving file from which data was imported and move it to
Archived
folder - Repeat until no files left in
New
folder.
My file structure is as follows:
All files in the New
folder are identical (except name) .xlsm
files. Each has a Defined Name
cell range called export_data
with the single row of cells I need to import into my Dashboard.xlsm
.
I would like the macro to use relative paths for the New
and Archived
folders as it would allow me to move the entire set of files anywhere and still work.
At present I have gotten as far as adapting as best I could the code from this post trying to get the macro to move the files:
Option Explicit
Const FOLDER_PATH = "C:\Users\OneDrive\Projects\Audit Sheet\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
rowTarget = 2
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
On Error GoTo errHandler
Application.ScreenUpdating = False
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
'Set wsSource = wbSource.Worksheets(1) 'EDIT IF NECESSARY
'import the data
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
'rowTarget = rowTarget + 1
sFile = Dir()
Loop
errHandler:
On Error Resume Next
Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
End Sub
Private Function FileFolderExists(strPath As String) As Boolean
If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function