Looping folders names from excel file vba - excel

I have a code that will copy the desired files that I want
here's the code
Dim saveFolder As String
Dim fname As String
saveFolder = "C:\Copied file"
folder = Workbooks("Macros.xlsb").Worksheets("folder").Range("A2")
FileName = Workbooks("Macros.xlsb").Worksheets("path").Range("B4")
Path = FileName & "\" & folder & "\Samples\*.xlsx"
file = Dir(Path)
Workbooks.Open Path
Sheets("Accounts").copy
ActiveWorkbook.SaveAs saveFolder & "\Accounts.xlsx", FileFormat:=51
Workbooks(file).Close
ActiveWorkbook.Close
it works well but I need to input manually the folder name in the cell column. But I'm clicking every after the macro is done for 1 folder only and so on.
I just want to know how to loop it.
this will be my worksheet(folder) for the folder names:
FOLDER
45
118
180
290
I want to loop the macro for each cells. so that I don't need to click/edit one by one the values. because the folder names can be changed momentarily.

Within the bounds of your question asking for a loop, you can try this ...
Dim saveFolder As String
Dim fname As String
Dim lastRow As Long
Dim i As Long
' Set this either statically or dynamically.
lastRow = 100
saveFolder = "C:\Copied file"
' Start from where you want either statically or dynamically.
For i = 4 To lastRow
folder = Workbooks("Macros.xlsb").Worksheets("folder").Range("A2")
Filename = Workbooks("Macros.xlsb").Worksheets("path").Range("B" & i)
Path = Filename & "\" & folder & "\Samples\*.xlsx"
file = Dir(Path)
Workbooks.Open Path
Sheets("Accounts").Copy
ActiveWorkbook.SaveAs saveFolder & "\Accounts.xlsx", FileFormat:=51
Workbooks(file).Close
Next
ActiveWorkbook.Close

for just copying files from one location to another, you do not need to open and saveAs on file :)
You can loop in folder names from top row to lastRow and process the folders one by one.
Find last row by
lastRow = wb.sheets("Folder").cells(wb.rows.count, 1).end(xlup).row
Now, loop through the folder name by for loop
for i=2 to lastRow
you can have your folder inside the loop like
for i=2 to lastRow
folder = Workbooks("Macros.xlsb").Worksheets("folder").Range("A" & i)
...
copy operations and filter here
...
next i

Related

How to copy data from only the new excel files that are saved in a predefined folder?

I want to copy specific range from excel files stored in a specific folder and paste it in another excel file.I am able to do so.However,every time i run the code it starts with the very first file in the folder.I want to copy data from only the files that haven't been updated before.Is there a way to do that?
EG:
"file1.xlsx" and "file2.xlsx" are in a folder. I want to copy data from the given files and paste it in "NewFile.xlsm" (I'm able to achieve this) However, if I add "file3.xlsx" and "file4.xlsx" in the folder and then run the macro, it copies data from "file1.xlsx" and "file2.xlsx" as well.I want it to copy data only from "file3.xlsx" and "file4.xlsx" this time as the data from previous 2 files is already saved.
(The code i have is given below)
Path = "C:\Users\National\Desktop\TEST Codes\PO\Excel\"
Filename = Dir(Path & "*.xls")
Do While Filename <> ""
If Filename = "Z master for PO.xlsm" Then
Exit Sub
End If
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
Sheets("DETAILED").Range("A3:S15").Copy
Application.DisplayAlerts = False
Application.ScreenUpdating = False
ActiveWorkbook.Close
Dim LASTROW As Long, WS As Worksheet, LS As Long
Set WS = Sheets("sheet1")
LASTROW = WS.Range("R" & Rows.Count).End(xlUp).Row + 1
WS.Range("A" & LASTROW).Select
ActiveSheet.Paste Destination:=WS.Range("A" & LASTROW)
Application.CutCopyMode = False
Filename = Dir()
Loop
Range("A7").Select
One way of doing this is by looking at the DateLastAccessed property, or the DateLastModified property. These are both properties of the File object, see this MS documentation.
You can set a minimum date/time, which should exclude the files you don't want processed.
Be sure to set the correct reference
Option Explicit
Sub GoThroughFiles()
Dim Path As String, Filename As String,
Dim fso, fileinfo
Set fso = CreateObject("Scripting.FileSystemObject")
Path = "C:\Users\National\Desktop\TEST Codes\PO\Excel\"
Filename = Dir(Path & "*.xls")
Set fileinfo = fso.GetFile(Path & Filename)
Do While Len(Filename) > 0
If fileinfo.DateLastAccessed > DateAdd("n", -5, Now) 'If the file was last accessed less than 5 minutes ago
'Do stuff with the file
End If
FileName = Dir()
Loop
End Sub
Furthermore, avoid using Select and Activate as using both will make your code prone to errors. Here is a thread on how to avoid it. Next to that, I added Option Explicit which makes sure you avoid other errors caused by, for example, spelling mistakes.

Excel VBA Dir() Error when file type changes

I'm trying to better understand the Dir function. I have a Dir loop to take action on all .csv files in the directory, but when the loop comes across another file type, like .txt, it will error instead of moving on to the next .csv. item.
This is the relevant portion of my code.
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
strWorkbook = Dir(strSourceExcelLocation & "*.csv*")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport)
'Get next workbook
strWorkbook = Dir
'Close Excel workbook without making changes
wbktoExport.Close False
Loop
So if there are only .csv files in the directory, then this works fine. When it comes across another file type, an error occurs.
The error is on line
strWorkbook = Dir
Run-time error 5: Invalid procedure call or argument
Am I missing something with the way I use the wildcards in the .csv at the beginning?
Thank you
Solved my issue.
The problem seems to have been because when I called another procedure, I had another Dir in that sub to create a new folder if one didn't already exist. So basically I had a Dir in a Dir, which apparently is bad.
I moved the folder creation part to the very beginning of my procedure, so it is executed before I begin the Dir for looping through all the CSV files.
Option Explicit
Sub Loop_Dir_for_Excel_Workbooks()
Dim strWorkbook As String, wbktoExport As Workbook, strSourceExcelLocation As String, fldr As String, strTargetPDFLocation As String, d As String
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\"
'***** Creating a folder to save the PDFs in. Naming the folder with today's date *****
d = Format(Date, "mm-dd-yyyy")
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\" & d & "\"
If Len(Dir(strTargetPDFLocation, vbDirectory)) = 0 Then MkDir strTargetPDFLocation
fldr = InputBox("Input the EXACT Folder Name that you want to create PDFs for")
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
'Search all Excel files in the directory with .xls, .xlsx, xlsm extensions
strWorkbook = Dir(strSourceExcelLocation & "*.csv")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport, strTargetPDFLocation)
'Close Excel workbook without making changes
wbktoExport.Close False
'Get next workbook
strWorkbook = Dir
Loop
End Sub
Try to hardcode the path and give it a try again. Probably the error is something really small in the hardcoding. E.g., in the code below, replace C:\Users\username\Desktop\AAA\ with the path of the file. Then run it. Do not forget the last \. It should work:
Sub TestMe()
Dim workbookPath As String
workbookPath = Dir("C:\Users\username\Desktop\AAA\" & "*.csv")
Do While Len(workbookPath) > 0
Debug.Print workbookPath
workbookPath = Dir
Loop
End Sub

Bulk rename worksheets to workbook (file) names in specfic folder

I have 90 Excel sheets in a folder: each Excel file has a unique name (company number) and contains only one worksheet. However the sheet name is generically named to 'Sheet1' in all files. Is there a VBA code that can rename all these sheets in this folder to their respective file name, minus the '.xlsx'?
Basically I want to combine all sheets to one file (I already have that VBA script). However before I can proceed with that, I have to rename all excel sheet names to their unique identifier (which is the file name).
I already looked online, but didn't see this script yet or saw this script for similar other purposes. Thanks in advance!
I found a solution online, credits to user VoG on https://www.mrexcel.com/forum/excel-questions/660913-vba-code-bulk-rename-first-worksheet-dependent-workbook-name.html
This is the solution. Change MyFolder = "C:\example" to respective folder
Sub RenSheets()
Dim MyFolder As String
Dim MyFile As String
Dim wbname As String
MyFolder = "C:\example"
MyFile = Dir(MyFolder & "\*.xls")
Application.ScreenUpdating = False
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
With ActiveWorkbook
wbname = Left(.Name, InStr(.Name, ".") - 1)
.Sheets(1).Name = wbname
.Close savechanges:=True
End With
MyFile = Dir
Loop
Application.ScreenUpdating = True
End Sub

Using Current Directory to retrieve data without opening Excel Workbook (Smarter Selective Imports w/VBA)

(Excel 2010)
I'm trying to grab specific lines from a variety of "target" workbooks in different but similar folders. I have found that I am able to pull this data when the source ("LM", the workbook the code is executing in, and that I want to pull the data to) and target workbooks are in the same folder without opening the target's workbook, but when they are in different locations (as they will be in practice) I receive a "Subscript out of range" error for the
LM.Worksheets("Sheet1").Range("B" & i + 1 & ":G" & i + 1).Value = _
Workbooks(filename).Worksheets("Sheet1").Range("B6:G6").Value
line. I have tried:
Using every variant & combination on pathname, dirname & filename, etc. as the argument for the latter Workbooks(). I have also had it MsgBox me the pieces and whole of pathname and filename to look at, which are error-free.
Replacing the latter Workbooks(filename) with a workbook variable (lets call it Targ), like LM (which works fine)
Changing the path with ChDir and ChDrive (& I have confirmed that the CurDir() is in fact the target directory when this is running) and doing the above
Using ThisWorkbook instead of LM for the call
Basically every permutation of the above ideas
Here is a stripped-down (because confidential stuff was in there) version of the code (which works fine if I un-comment Workbooks.Open and Workbooks.Close, but I want a more efficient method since this is a busy network and people are in-and-out of these files all the time. The fact that I can do this without opening the files if they're in the same folder tells me I'm onto something...)
Sub Import()
Dim directory As String, fileName As String, LM As Workbook, i as Integer
Set LM = Workbooks("LM.xlsm")
i = 1
Dim DirArray As Variant
'this is the array that handles the variations on the path, doesn't seem to be the problem
DirArray = LM.Worksheets("Sheet2").Range("DirTable")
Do While i <= UBound(DirArray)
directory = DirArray(i, 1)
dirname = "C:\blahblahblah"
fileName = Dir(dirname & "*.xl??")
pathname = dirname & fileName
ChDir dirname
' Workbooks.Open (dirname & fileName)
LM.Worksheets("Sheet1").Range("B" & i + 1 & ":G" & i + 1).Value = _
Workbooks(filename).Worksheets("Sheet1").Range("B6:G6").Value
i = i + 1
' Workbooks(fileName).Close
Loop
End Sub
If I could just figure out what is different when they're in the same folder! Navigating with ChDir and ChDrive doesn't seem to do any good...
It's unclear exactly what you want to do, but this should be a working version of your posted code.
Is there only one Excel file per folder? Did you want to use directory in place of the hard-coded DIRNAME ?
Sub Import()
Const DIRNAME As String = "C:\blahblahblah\"
Dim directory As String, fileName As String, LM As Workbook, i As Integer
Dim DirArray As Variant, wb As Workbook
Set LM = Workbooks("LM.xlsm") 'ThisWorkbook ?
DirArray = LM.Worksheets("Sheet2").Range("DirTable").Value
For i = 1 To UBound(DirArray, 1)
directory = DirArray(i, 1) 'what are these values ?
fileName = Dir(DIRNAME & "*.xl??")
If fileName <> "" Then
'ChDir dirname '<< you do not need this if you pass the full path to Open...
Set wb = Workbooks.Open(filename:=DIRNAME & fileName, _
ReadOnly:=True, UpdateLinks:=0)
LM.Worksheets("Sheet1").Range("B" & (i + 1) & ":G" & (i + 1)).Value = _
wb.Worksheets("Sheet1").Range("B6:G6").Value
wb.Close False 'no save
End If
Next
End Sub

Connecting two path strings to get the final path?

I'm trying to save excel file into a specific path.
So basically, when I click the button, I'm creating a folder, and want to save the file inside that folder.
The created folder has the current month as name. I'm trying to save into that current month folder.
'Create folder as Month Name. Save filename as date inside "month".
Dim sDate As String = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
Dim sMonth As String = DateTime.Now.ToString("MMMM")
Dim sFolder = Application.StartupPath & "\Resources\Excel\"
My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
Dim sfinal = Path.Combine(sFolder, sMonth)
xlSh.SaveAs(sfinal & Format(sDate) & ".xlsx")
xlApp.Workbooks.Close()
xlApp.Quit()
As it is, this code doesn't give me any errors. But instead of creating a folder named "March" <-current month and saving inside it, it saves the file in \Excel\ and it also creates folder in the same place.
you could use the following function (similar to .NET System.IO.Path.Combine)
Function PathCombine(path1 As String, path2 As String)
Dim combined As String
combined = path1
If Right$(path1, 1) <> Application.PathSeparator Then
combined = combined & Application.PathSeparator
End If
combined = combined & path2
PathCombine = combined
End Function
Hope this helps!
After long hours of excruciating pain, I've finally did it!
Apparently I was missing an "\"
Since "sMonth" became dynamic name, which later I wanted to use as path, and save files in that folder. I needed to simply put that "\" after sMonth, to tell it to save inside it.
Before I realize this... I've broken down, simplified the code as much as I could so I can logically connect the pieces. What I ended up with, is something slightly different. Now the SaveAS properly saves the file inside the new folder.
Dim sDate As String
sDate = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
Dim sMonth As String
sMonth = DateTime.Now.ToString("MMMM")
Dim sFileName As String
sFileName = sDate + ".xlsx"
Dim sFolder As String
sFolder = Application.StartupPath & "\Resources\Excel\"
Dim sfinal As String
sfinal = (sFolder & sMonth & "\") '<- this thingie here o.O
My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
xlSh.SaveAs(sfinal & Format(sFileName))
xlApp.Workbooks.Close()
xlApp.Quit()
Thanks for the help.
You don't appear to actually be setting the save path to the created directory. Instead, I believe you're appending the month to the beginning of the file name in the xlSh.SaveAs(sFinal & Format(sDate) & ".xlsx"). Basically (though I'm not sure of the specific command) you need to navigate to the folder you created after you create it. Probably something to the format of
My.Computer.FileSystem.ChangeDirectory(sFolder & Format(sMonth))
though I don't know that that specific command actually exists as I wrote it.
To those who have been wondering wtf I was doing with all this, here is the full sub. And if anyone needs something similar. Thanks for the support. Problem has been resolved.
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
Dim xlApp As Excel.Application
Dim xlSh As Excel.Worksheet
xlApp = New Excel.Application
xlApp.Workbooks.Add()
xlSh = xlApp.Workbooks(1).Worksheets(1)
'Items from listbox1 to be exported into excel, second row, second column.
Dim row As Integer = 2
Dim col As Integer = 2
For i As Integer = 0 To ListBox1.Items.Count - 1
xlSh.Cells(row, col) = ListBox1.Items(i)
row = row + 1
Next
row += 1
col = 1
'Items from listbox2 to be exported into excel, second row, third column.
Dim row2 As Integer = 2
Dim col2 As Integer = 3
For i As Integer = 0 To ListBox2.Items.Count - 1
xlSh.Cells(row2, col2) = ListBox2.Items(i)
row2 = row2 + 1
Next
row2 += 1
col2 = 1
'Create folder as Month Name. Save filename as date inside that folder.
'Make filename be yyyy-MM-DD_HH-mm-ss
Dim sDate As String
sDate = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
'This will be used as name for the new folder.
Dim sMonth As String
sMonth = DateTime.Now.ToString("MMMM")
'Filename + extension.
Dim sFileName As String
sFileName = sDate + ".xlsx"
'This is the path.
Dim sFolder As String
sFolder = Application.StartupPath & "\Resources\Excel\"
'This is the path combined with sMonth to make the final path.
Dim sfinal As String
sfinal = (sFolder & sMonth & "\")
'Check if folder with the name sMonth already exists.
If Dir(sFolder, vbDirectory) = sMonth Then
'If it exist, then simply save the file inside the folder.
xlSh.SaveAs(sfinal & Format(sFileName))
Else
'If it doesn't exist:
'This is the creation of sMonth folder, inside "\excel\.
My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
'This saves the excel file at path sfinal, with filename of sFileName
xlSh.SaveAs(sfinal & Format(sFileName))
End If
'Close everything.
xlApp.Workbooks.Close()
xlApp.Quit()
End Sub
I find this method to be much easier.
Create a FileSystemObject and use BuildPath Method, like so:
Set fs = CreateObject("Scripting.FileSystemObject")
skPath = fs.BuildPath(ActiveDocument.Path, "Survival Story of Sword King")
Attention: ActiveDocument.Path is current directory in Word and does not work in excel or other. for excel it would be ActiveWorkbook.Path
My point is some methods or namespace are application specific.

Resources