VBA - Open files in folder and print names - vba

I want to open all of the files in a certain folder and have it print out the names of those files.
I have set up a code that opens the files but I cannot get it to print the name. I have a separate code that will print the name but will only open one file. I'm failing at combining the two together correctly. Any ideas?
Code that opens all Excel files:
‘set path to progress folder
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
MyFolder = “C:\Users\trembos\Documents\TDS\progress"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Workbooks.Open fileName:=MyFolder & "\" & MyFile
MyFile = Dir
Loop
End Sub
Code that prints one file name:
'set path to TDS_Working
Sub TDS()
Workbooks.Open ("C:\Users\trembos\Documents\TDS\progress")
End Sub
'set up dim
Sub LoopThroughDirectory()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
'create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'get the folder object
Set objFolder = objFSO.GetFolder("C:\Users\trembos\Documents\TDS\progress\")
i = 1
'loop through directory file and print names
For Each objFile In objFolder.Files
'print file name
Cells(i + 1, 1) = objFile.Name
Next objFile
End Sub

This should work smoothly :
Sub LoopThroughDirectory()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim MyFolder As String
Dim Sht As Worksheet
Dim i As Integer
MyFolder = "C:\Users\trembos\Documents\TDS\progress\"
Set Sht = ActiveSheet
'create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'get the folder object
Set objFolder = objFSO.GetFolder(MyFolder)
i = 1
'loop through directory file and print names
For Each objFile In objFolder.Files
If LCase(Right(objFile.Name, 3)) <> "xls" And LCase(Left(Right(objFile.Name, 4), 3)) <> "xls" Then
Else
'print file name
Sht.Cells(i + 1, 1) = objFile.Name
i = i + 1
Workbooks.Open Filename:=MyFolder & objFile.Name
End If
Next objFile
End Sub

You just need to iterate i inside the loop: i=i+1.

‘set path to progress folder
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
ActiveSheet.Unprotect ("password")
MyFolder = “C:\Users\trembos\Documents\TDS\progress"
MyFile = Dir(MyFolder & "\*.xlsx")
i=1
Do While MyFile <> ""
Workbooks.Open fileName:=MyFolder & "\" & MyFile
MyFile = Dir
Cells(i + 1, 1) =Myfile
i=i+1
Loop
ActiveSheet.Protect ("password")
End Sub
Does this not work?

Related

Opening the youngest file in a folder VBA

Hi I am trying to open the latest file (date modified) in a folder. The code uses a loop to go through the files and find the latest modified which it does however when it comes to open the file using 'Workbooks.Open strFilename' it says the file (which it has already identified as the 'youngest' file could not be found. This doesn't make sense to me as the error message says the file 'test young' - the file name could not be found, but it clearly found it during the loop.
Sub copynewdata()
Dim FileSys As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dteFile As Date
Dim Ref As Object, CheckRefEnabled%
CheckRefEnabled = 0
With ThisWorkbook
For Each Ref In .VBProject.References
If Ref.Name = "Scripting" Then
CheckRefEnabled = 1
Exit For
End If
Next Ref
If CheckRefEnabled = 0 Then
.VBProject.References.AddFromGUID "{420B2830-E718-11CF-893D-00A0C9054228}", 1, 0
End If
End With
'set path for files - change for your folder
Const myDir As String = "\\C:\Test"
'set up filesys objects
Set FileSys = New FileSystemObject
Set myFolder = FileSys.GetFolder(myDir)
'loop through each file and get date last modified. If largest date then store Filename
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
If objFile.DateLastModified > dteFile Then
dteFile = objFile.DateLastModified
strFilename = objFile.Name
End If
Next objFile
Workbooks.Open strFilename
'Set Source_Workbook = Workbooks(strFilename).Open(Target_Path)
Set FileSys = Nothing
Set myFolder = Nothing
End Sub
Can anyone help with this?
In strFilename, you have the name of the file - but without the path. Change the open-command to
Workbooks.Open myDir & "\" & strFilename

Auto Hyperlink the extracted files

I am working with a code which can extract entire path of a pdf files and display of active workbook.
But problem is the extracted files are not hyperlinked i.e. I cant open the files directly on clicking on the that cell. Is there any way it gets automatically hyperlinked so that one click opens the files directly from excel.
Below is the code:
Sub ReadFiles()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder(Range("C1").Value)
i = 1
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
If Right(objFile.Path, 3) = "pdf" Then
'print file path
Cells(i + 2, 13) = objFile.Path
i = i + 1
End If
Next objFile
End Sub
This should work, replace "WorksheetName" with the name of your worksheet:
Sub ReadFiles()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder(Range("C1").Value)
i = 1
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
If Right(objFile.Path, 3) = "pdf" Then
'print file path
Cells(i + 2, 13) = objFile.Path
Sheets("WorksheetName").Hyperlinks.Add _
Anchor:= Sheets("WorksheetName").Cells(i + 2, 13), _
Address:= objFile.Path
i = i + 1
End If
Next objFile
End Sub
After you print file path add this: cells(i + 2,13).select ActiveCell.Hyperlinks.Add ActiveCell, ActiveCell

Copy cell J1 from multiple files and paste into column of masterfile

I currently have this code which will take files from a folder, open each one, print its name into the first column of my "Master file" close it and loop through the entire folder that way.
In each file that is opened, there is information in cell J1 that I would like to copy and paste into column 3 of my "master file". The code works but will only paste the desired info from J1 into C2 over and over so the information keeps being written over. I need to increment down the list so the info from J1 is printed into the same row as the name of the file.
Any ideas?
Sub LoopThroughDirectory()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim MyFolder As String
Dim Sht As Worksheet
Dim i As Integer
MyFolder = "C:\Users\trembos\Documents\TDS\progress\"
Set Sht = ActiveSheet
'create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'get the folder object
Set objFolder = objFSO.GetFolder(MyFolder)
i = 1
'loop through directory file and print names
For Each objFile In objFolder.Files
If LCase(Right(objFile.Name, 3)) <> "xls" And LCase(Left(Right(objFile.Name, 4), 3)) <> "xls" Then
Else
'print file name
Sht.Cells(i + 1, 1) = objFile.Name
i = i + 1
Workbooks.Open fileName:=MyFolder & objFile.Name
End If
'Get TDS name of open file
Dim NewWorkbook As Workbook
Set NewWorkbook = Workbooks.Open(fileName:=MyFolder & objFile.Name)
Range("J1").Select
Selection.Copy
Windows("masterfile.xlsm").Activate
'
'
' BELOW COMMENT NEEDS TO BE CHANGED TO INCREMENTING VALUES
Range("D2").Select
ActiveSheet.Paste
NewWorkbook.Close
Next objFile
End Sub
I do some modification on your code and it shows the result that needed by you. Please take note that your macro may spoil if your folder got other extension of files. You may increase the performance of this macro by using the following code : Application.ScreenUpdating = False
Option Explicit
Dim MyMasterWorkbook As Workbook
Dim MyDataWorkbook As Workbook
Dim MyMasterWorksheet As Worksheet
Dim MyDataWorksheet As Worksheet
Sub LoopThroughDirectory()
Set MyMasterWorkbook = Workbooks(ActiveWorkbook.Name)
Set MyMasterWorksheet = MyMasterWorkbook.ActiveSheet
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim MyDataFolder As String
Dim MyFilePointer As Byte
MyDataFolder = "C:\Users\lengkgan\Desktop\Testing\"
MyFilePointer = 1
'create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'get the data folder object
Set objFolder = objFSO.GetFolder(MyDataFolder)
'loop through directory file and print names
For Each objFile In objFolder.Files
If LCase(Right(objFile.Name, 3)) <> "xls" And LCase(Left(Right(objFile.Name, 4), 3)) <> "xls" Then
Else
'print file name
MyMasterWorksheet.Cells(MyFilePointer + 1, 1) = objFile.Name
MyFilePointer = MyFilePointer + 1
Workbooks.Open Filename:=MyDataFolder & objFile.Name
End If
'Get TDS name of open file
Set MyDataWorkbook = Workbooks.Open(Filename:=MyDataFolder & objFile.Name)
Set MyDataWorksheet = MyDataWorkbook.ActiveSheet
'Get the value of J1
MyMasterWorksheet.Range("C" & MyFilePointer).Value = MyDataWorksheet.Range("J1").Value
'close the workbook without saving it
MyDataWorkbook.Close (False)
Next objFile
End Sub
IF the sheetname is consistent across the files ie "Sheet1", you can do this without opening the files:
Sub LoopThroughDirectory()
Dim objFSO As Object, objFolder As Object, objFile As Object, MyFolder As String, Sht As Worksheet
MyFolder = "C:\Users\trembos\Documents\TDS\progress\"
Set Sht = ActiveSheet
'create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'get the folder object
Set objFolder = objFSO.GetFolder(MyFolder)
'loop through directory file and print names
For Each objFile In objFolder.Files
If Not LCase(Right(objFile.Name, 3)) <> "xls" And Not LCase(Left(Right(objFile.Name, 4), 3)) <> "xls" Then
'print file name
Sht.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Formula = objFile.Name
Sht.Cells(Rows.Count, 4).End(xlUp).Offset(1, 0).Formula = ExecuteExcel4Macro("'" & MyFolder & objFile.Name & "Sheet1'!R1C10") 'This reads from a closed file
End If
Next objFile
End Sub
This is the solution that works:
'print J1 values to Column 4 of masterfile
With WB
For Each ws In .Worksheets
StartSht.Cells(i + 1, 1) = objFile.Name
With ws
.Range("J1").Copy StartSht.Cells(i + 1, 4)
End With
i = i + 1
'move to next file
Next ws
'close, do not save any changes to the opened files
.Close SaveChanges:=False
End With

VBA loop through directory

**Hi All,
I would to incorporate into the below script the ability to search through files and export ONLY the data from the most recent file in folder. I will be adding a new file every week into folder so do not want the old data range to be copied across.
Can someone please help?**
Sub loopthroughdirectory()
Dim myfile As String
Dim erow
fileroot = "C:\Users\ramandeepm\Desktop\consolidate\"
myfilename = Dir("C:\Users\ramandeepm\Desktop\consolidate\")
Do While Len(myfilename) > 7
If myfilename = "zmaster.xlsm" Then
Exit Sub
End If
myfile = fileroot & myfilename
Workbooks.Open (myfile)
Range("range").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("sheet1").Range(Cells(erow, 1), Cells(erow, 4))
myfilename = Dir()
Loop
End Sub
If you use FileSystemObject it can be done using the .DateLastModified property. The below code should get you started:
Untested
Dim FSO As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dtFile As Date
'set folder location
Const myDir As String = "C:\Users\ramandeepm\Desktop\consolidate"
'set up filesys objects
Set FSO = New FileSystemObject
Set myFolder = FSO.GetFolder(myDir)
'loop through each file and get date last modified. If largest date then store Filename
dtFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
If Len(objFile.Name) > 7 Then
If objFile.DateLastModified > dtFile Then
dtFile = objFile.DateLastModified
strFilename = objFile.Name
End If
End If
Next objFile
Workbooks.Open strFilename
Note: This code is looking for the most recent modified date. So this will only work if the newest file was created after any modifications in other files in the folder. Also, you may need to enable the Microsoft Scripting Runtime library reference.

How to use text file to load file paths to excel macro

Ok, I have a macro in excel which is working perfectly.
Sub FindOpenFiles()
Dim FSO As Scripting.FileSystemObject, folder As Scripting.folder, file As Scripting.file, wb As Workbook, sh As Worksheet
Dim directory As String
directory = "O:\test\1"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set folder = FSO.GetFolder(directory)
For Each file In folder.Files
If Mid(file.Name, InStrRev(file.Name, ".") + 1) = "xls" Then
Workbooks.Open directory & Application.PathSeparator & file.Name
Set wb = Workbooks("Equipment Further Documentation List.xls")
For Each sh In Workbooks("1.xls").Worksheets
sh.Copy After:=wb.Sheets(wb.Sheets.Count)
Next sh
ActiveWorkbook.Close SaveChanges:=True
ActiveWorkbook.CheckCompatibility = False
End If
Next file
End Sub
I want to modify it so I could read in file path from a text file run the macro and change the file path to another one listed in the text file and so on. As soon as the text file reaches EOF, stop the macro.
How should I change the code to make it happen.
directory = "O:\test\1"
The file paths in the .txt file are separated by return.
Thanks.
Adapt as you see fit but you should get the idea!
Const ForReading = 1
Set oFSO = New FileSystemObject
Dim txtStream As textStream
Set txtStream = oFSO.OpenTextFile("C:\....\PathtoFiles.txt", ForReading)
Do Until txtStream.AtEndOfStream
strNextLine = txtStream.ReadLine
If strNextLine <> "" Then
' Do something?
End If
Loop
txtStream.Close
The full answer is :
Sub FindOpenFiles()
Const ForReading = 1
Set oFSO = New FileSystemObject
Dim txtStream As TextStream
Dim FSO As Scripting.FileSystemObject, folder As Scripting.folder, file As Scripting.file, wb As Workbook, sh As Worksheet
Dim directory As String
Set txtStream = oFSO.OpenTextFile("C:\Users\GrzegoP\Desktop\Project\test\paths.txt", ForReading)
Do Until txtStream.AtEndOfStream
strNextLine = txtStream.ReadLine
If strNextLine <> "" Then
Set FSO = CreateObject("Scripting.FileSystemObject")
Set folder = FSO.GetFolder(strNextLine)
For Each file In folder.Files
If Mid(file.Name, InStrRev(file.Name, ".") + 1) = "xls" Then
Workbooks.Open directory & Application.PathSeparator & file.Name
Set wb = Workbooks("Equipment Further Documentation List.xls")
For Each sh In Workbooks("1.xls").Worksheets
sh.Copy After:=wb.Sheets(wb.Sheets.Count)
Next sh
ActiveWorkbook.Close SaveChanges:=True
ActiveWorkbook.CheckCompatibility = False
End If
End If
Next file
Loop
txtStream.Close
End Sub