Is there a way to list file names across different directories in an excel sheet, with links (so one can click on the link beside the file name and the file would open)?
I'm ready to write a script, but I don't know of any particular method or command.
I don't want to be typing the whole thing.
I don't care about directory/tree structure, but file link should be present.
There is one directory which contains lots of other folders which contain the files I need to list, mostly *.pdf's.
Any help appreciated. Thanks!
You can use below code to get File name and File path Set main folder to strFolderPath
'Global Declaration for Start Row
Public lngRow As Long
Sub pReadAllFilesInDirectory()
Dim strFolderPath As String
Dim BlnInclude_subfolder As Boolean
'Set Path here
strFolderPath = "C:\"
'set start row
lngRow = 1
'Set this true if you want list of sub-folders as well
BlnInclude_subfolder = True
'---------- Reading of files in folders and sub-folders------
Call ListMyFiles(strFolderPath, BlnInclude_subfolder)
'---------- Reading of files in folders and sub-folders------
End Sub
Sub ListMyFiles(mySourcePath As String, blnIncludeSubfolders As Boolean)
Dim MyObject As Object
Dim mySource As Object
Dim mySubFolder As Object
Dim myfile As Object
Dim iCol As Long
Set MyObject = CreateObject("Scripting.FileSystemObject")
Set mySource = MyObject.GetFolder(mySourcePath)
'Loop in each file in Folder
For Each myfile In mySource.Files
iCol = 1
Sheet1.Cells(lngRow, iCol).Value = myfile.Name 'File Name
iCol = iCol + 1
Sheet1.Cells(lngRow, iCol).Value = myfile.Path 'File Path/Location
lngRow = lngRow + 1
Next
If blnIncludeSubfolders Then
For Each mySubFolder In mySource.SubFolders
Call ListMyFiles(mySubFolder.Path, True)
Next
End If
End Sub
A quick seach yielded this answer I believe you are looking for.
Sub Example1()
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("D:\Stuff\Business\Temp")
i = 1
'loops through each file in the directory
For Each objFile In objFolder.Files
'select cell
Range(Cells(i + 1, 1), Cells(i + 1, 1)).Select
'create hyperlink in selected cell
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
objFile.Path, _
TextToDisplay:=objFile.Name
i = i + 1
Next objFile
End Sub
Related
I have this code thanks to Import text files contents and name of text file into Excel with a macro
Option Explicit
Sub Import_video_txt_files()
' ADD REFERENCE TO MICROSOFT FILE SYSTEM OBJECT
Dim objFSO As FileSystemObject
Dim objFolder As folder
Dim objFile As file
Dim objTextStream As TextStream
Dim strPath As String
Dim i As Long
' Specify the folder...
strPath = "C:\Users\User\Desktop\TEST\"
' Use Microsoft Scripting runtime.
Set objFSO = New FileSystemObject
Set objFolder = objFSO.GetFolder(strPath)
' Check extension of each file in folder.
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile.Name) = "txt" Then
Cells(i + 2, 1) = objFile.Name
Set objTextStream = objFile.OpenAsTextStream(ForReading)
Cells(i + 2, 2) = objTextStream.ReadAll
i = i + 1
End If
Next
End Sub
However now I need to expand the function.
The text file has all the information on one line.
For example: grey, red, blue|408.95|14165.849841859
I am using this separator |
I would like to be able to import all the information from the text file and separate them using | and put them in their appropriate cells as illustrated in the image below.
Try,
Sub Import_video_txt_files()
' ADD REFERENCE TO MICROSOFT FILE SYSTEM OBJECT
Dim objFSO As FileSystemObject
Dim objFolder As folder
Dim objFile As file
Dim objTextStream As TextStream
Dim strPath As String
Dim i As Long
Dim s As String, vSplit
' Specify the folder...
strPath = "C:\Users\User\Desktop\TEST\"
' Use Microsoft Scripting runtime.
Set objFSO = New FileSystemObject
Set objFolder = objFSO.GetFolder(strPath)
' Check extension of each file in folder.
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile.Name) = "txt" Then
Cells(i + 2, 1) = objFile.Name
Set objTextStream = objFile.OpenAsTextStream(ForReading)
'Cells(i + 2, 2) = objTextStream.ReadAll
s = objTextStream.ReadAll
vSplit = Split(s, "|")
Range("b" & i + 2).Resize(1, UBound(vSplit) + 1) = vSplit
i = i + 1
End If
Next
End Sub
After importing your pipe data, run this short macro:
Sub PipeKleaner()
Dim i As Long, N As Long, s As String, arr
Dim v As String
N = Cells(Rows.Count, "B").End(xlUp).Row
For i = 1 To N
v = Cells(i, "B").Value
arr = Split(v, "|")
Cells(i, "C").Resize(1, UBound(arr) + 1).Value = arr
Next i
End Sub
NOTE:
This code does the parsing into column C and beyond rather than over-writing column B. If you don't need the original data, just change the Resize() code-line.
I'm trying to create a range name in a number of excel files, and then write the file names and paths out to another excel. The files/paths are written correctly, but the range name doesn't appear to be created in the file. Can you tell me where I'm going wrong?
Sub directlisting()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim cell As Range
Dim RangeName As String
Dim CellName As String
Dim i As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("\\xxxxxxxxxxx\testdata\Transfer")
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'open file if an Excel file
If Right(objFile, 4) = "xls*" Or Right(objFile, 3) = "xl*" Then
Application.Workbooks.Open (objFile)
'create range name
RangeName = "PVS"
CellName = "A4:AG27"
Set cell = Worksheets("PVS").Range(CellName)
objFile.Names.Add Name:=RangeName, RefersTo:=cell
'Save the file
Application.DisplayAlerts = False
objFile.Save
objFile.Close
Application.DisplayAlerts = True
End If
'print file name
Cells(i + 1, 1) = objFile.Name
'print file path
Cells(i + 1, 2) = objFile.path
i = i + 1
Next objFile
End If
End Sub
I tested this and it seemed to work for me. The main idea was to be more explicit with the workbook/worksheets and what you're calling them on:
Sub directlisting()
Dim objFSO As Object, objFolder As Object, objFile As Object
Dim cell As Range
Dim RangeName As String, CellName As String
Dim i As Integer
Dim tempWB As Workbook, mainWB As Workbook
Dim mainWS As Worksheet
'Assuming this is running from a "main" workbook
Set mainWB = ActiveWorkbook
Set mainWS = mainWB.ActiveSheet
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("D:\User\Documents\Test") ' CHANGE TO YOUR PATH
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'open file if an Excel file
If Right(objFile, 4) = "xlsx" Or Right(objFile, 3) = "xl*" Then
Set tempWB = Application.Workbooks.Open(objFile)
'create range name
RangeName = "PVS"
CellName = "A4:AG27"
Set cell = tempWB.Worksheets("PVS").Range(CellName)
'ActiveWorkbook.Names.Add Name:="PVS", RefersToR1C1:="=PVS!R11C8:R18C14"
tempWB.Names.Add Name:=RangeName, RefersTo:=cell
'print file name
mainWS.Cells(i + 1, 1) = tempWB.Name
'print file path
mainWS.Cells(i + 1, 2) = tempWB.Path
i = i + 1
'Save the file
Application.DisplayAlerts = False
tempWB.Save
tempWB.Close
Application.DisplayAlerts = True
End If ' Right (objFile, 4) ...
Next objFile
End Sub
Small note: I had to change the ... = "xls*" Or Right ... to ... = "xlsx" Or ..., because for some reason it wouldn't open the .xlsx file. Curious. In any case, let me know if you get any errors or weird issues!
Also, I moved the part where you save the workbook name and path inside the If statement, so only if the file opens, will it mark it. Just tweak that line if you want to note every file, whether or not it opens.
I previously got help to write read through several textfiles in a folder and organize the data in a spreadsheet. I got this script from #trincot that worked well for my need. How to import specific text from files in to excel?
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder, file As file, FileText As TextStream
Dim TextLine As String
Dim cl As Range
Dim num As Long ' numerical part of key, as in "Ann:"
Dim col As Long ' target column in Excel sheet
Dim key As String ' Part before ":"
Dim value As String ' Part after ":"
' Get a FileSystem object
Set fso = New FileSystemObject
' Get the directory you want
Set folder = fso.GetFolder("D:\YourDirectory\")
' Set the starting point to write the data to
' Don't write in first row where titles are
Set cl = ActiveSheet.Cells(2, 1)
' Loop thru all files in the folder
For Each file In folder.Files
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine 'read line
key = Split(TextLine & ":", ":")(0)
value = Trim(Mid(TextLine, Len(key)+2))
num = Val(Mid(key,2))
If num Then key = Replace(key, num, "") ' Remove number from key
col = 0
If key = "From" Then col = 1
If key = "Date" Then col = 2
If key = "A" Then col = 2 + num
If col Then
cl.Offset(, col-1).Value = value ' Fill cell
End If
Loop
' Clean up
FileText.Close
' Next row
Set cl = cl.Offset(1)
Next file
End Sub
The problem I figured out afterwards was that my textfiles will in time start to be stored in subfolders within a subfolder, and this script is not written to handle this.
I found this script by #Cor_Blimey here Loop Through All Subfolders Using VBA
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("your folder path variable") 'obviously replace
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
'...insert any file processing code here...
Next oFile
Loop
End Sub
And the two answers here Loop through all subfolders and files under a folder and write the last modifed date information to an Excel spreadsheet by #L42 and #chris nielsen.
I also tried a bit with TraversFolder function, but I have not been able to incorporate any of these solutions into my existing script. Any help would be much appreciated!
Put your function in section marked "HERE COMES YOUR READING CODE
Function is one of mine I used in projects. I deleted the surplus code and it should do its task.
Sub index()
ThisWorkbook.Save
DoEvents
Dim intResult As Integer
Dim strPath As String
Dim objFSO As Object
Dim intCountRows As Integer
Application.FileDialog(msoFileDialogFolderPicker).Title = "Vyberte prosím složku"
Application.FileDialog(msoFileDialogFolderPicker).ButtonName = "Vybrat složku"
Application.FileDialog(msoFileDialogFolderPicker).AllowMultiSelect = True
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
If intResult = 0 Then
End
End If
For Each Item In Application.FileDialog(msoFileDialogFolderPicker).SelectedItems
strPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) 'ulož cestu ke složce
Set objFSO = CreateObject("Scripting.FileSystemObject")
intCountRows = GetAllFiles(strPath, ROW_FIRST, objFSO)
Call GetAllFolders(strPath, objFSO, intCountRows)
Next Item
End Sub
Private Function GetAllFiles(ByVal strPath As String, ByVal intRow As Integer, ByRef objFSO As Object) As Integer
DoEvents
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
i = intRow + 1
Set objFolder = objFSO.GetFolder(strPath)
For Each objFile In objFolder.Files
If Right(objFile.Name, 3) = "txt" Then
'HERE COMES YOU READING CODE
i = i + 1
End If
Next objFile
GetAllFiles = i + ROW_FIRST - 1
End Function
Private Sub GetAllFolders(ByVal strFolder As String, ByRef objFSO As Object, ByRef intRow As Integer)
DoEvents
Dim objFolder As Object
Dim objSubFolder As Object
Set objFolder = objFSO.GetFolder(strFolder)
For Each objSubFolder In objFolder.subfolders
intRow = GetAllFiles(objSubFolder.Path, intRow, objFSO)
Call GetAllFolders(objSubFolder.Path, objFSO, intRow)
Next objSubFolder
End Sub
I need to open a few .zip files, view a specific .txt and write what's inside of this .txt file to an Excel workbook, and the name of the .zip will be in the same row in Excel.
Example:
The first row is the name of the .zip file and in the first row and second column will be the content of the .txt file.
I have part of the code. It says code error 91.
Sub Text()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Dim strDate As String
Dim I As Long
Dim num As Long
Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
MultiSelect:=True)
If IsArray(Fname) = False Then
'Do nothing
Else
'Root folder for the new folder.
'You can also use DefPath = "C:\Users\Ron\test\"
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
For Each fileNameInZip In oApp.Namespace(Fname).Items
If LCase(fileNameInZip) Like LCase("md5.txt") Then
'Open "md5.txt" For Input As #1
'Do Until EOF(1)
'Line Input #1, textline
' text = text & textline
' Loop
' Close #1
' Range("B1").Value = Mid(text, 1, 32)
' Range("A1").Value = Dir(Fname)
End If
Next
End If
End Sub
I tried to make a loop to open every file md5.txt in every zip that I have to open and take what's inside of the md5.txt
Here is an example of looping through your cells and getting the zip file, extracting the contents, and reading the file. You may need to adjust the path to the zip file or it will default to what ever file the excel document is started in. If you put the whole path to the zip in column A then you would not need to make an adjustment.
Edit was made to reflect the name of the file md5.txt and place contents in second column.
Sub GetData()
Dim iRow As Integer 'row counter
Dim iCol As Integer 'column counter
Dim savePath As String 'place to save the extracted files
Dim fileContents As String 'contents of the file
Dim fso As FileSystemObject 'FileSystemObject to work with files
iRow = 1 'start at first row
iCol = 1 'start at frist column
'set the save path to the temp folder
savePath = Environ("TEMP")
'create the filesystem object
Set fso = New FileSystemObject
Do While ActiveSheet.Cells(iRow, iCol).Value <> ""
fileContents = fso.OpenTextFile(UnzipFile(savePath, ActiveSheet.Cells(iRow, iCol).Value, "md5.txt"), ForReading).ReadAll
ActiveSheet.Cells(iRow, iCol + 1).Value = fileContents
iRow = iRow + 1
Loop
'free the memory
Set fso = Nothing
End Sub
Function UnzipFile(savePath As String, zipName As String, fileName As String) As String
Dim oApp As Shell
Dim strFile As String
'get a shell object
Set oApp = CreateObject("Shell.Application")
'check to see if the zip contains items
If oApp.Namespace(zipName).Items.Count > 0 Then
Dim i As Integer
'loop through all the items in the zip file
For i = 0 To oApp.Namespace(zipName).Items.Count - 1
'check to see if it is the txt file
If UCase(oApp.Namespace(zipName).Items.Item(i)) = UCase(filename) Then
'save the files to the new location
oApp.Namespace(savePath).CopyHere oApp.Namespace(zipName).Items.Item(i)
'set the location of the file
UnzipFile = savePath & "\" & fileName
'exit the function
Exit Function
End If
Next i
End If
'free memory
Set oApp = Nothing
End Function
So I was trying to create a list of excel files in a folder (file name and path) and then use a For loop to copy and paste a specified worksheet for all of the files listed into a specified worksheet in the excel workbook that contains the macro. So far everything works except for the fact that the same file keeps getting copied and pasted over instead of all the files. The macro loops for the correct number of times, but it's not using all the excel files.
Here's the code:
First part for listing the files in the folder
Private Sub btn_LeaveReport()
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("D:\Administration\Time Sheets")
i = 2
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'print file name
Cells(i + 1, 2) = objFile.Name
'print file path
Cells(i + 1, 3) = objFile.Path
i = i + 1
Next objFile
End Sub
and this is the part for the loop
Private Sub btn_PullData()
'Declared Variables
Dim wbk As Workbook
Dim i As Integer
Dim StartAt As Integer
Dim EndAt As Integer
Dim CopyPath As String
Dim CopyPathRow As Integer
Dim iRow As Integer
'Ranges
StartAt = 1
EndAt = Val(ThisWorkbook.Worksheets("LeaveReport").Range("A1"))
CopyPathRow = 3
CopyPath = ThisWorkbook.Worksheets("LeaveReport").Range("C" & CopyPathRow)
iRow = 3
'Loop de loop
For i = StartAt To EndAt
Application.ScreenUpdating = False
Set wbk = Workbooks.Open(CopyPath)
Sheets("TIMESHEET").Select
Range("C12:S34").Select
Selection.Copy
ThisWorkbook.Activate
Sheets("Pastebin").Select
Range("a" & iRow).PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
iRow = iRow + 39
CopyPathRow = CopyPathRow + 1
wbk.Close True
Next i
Sheets("Pastebin").Select
Range("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Application.ScreenUpdating = True
MsgBox "Timesheet Data Imported"
End Sub
Based on the source of the error, i.e. same file being used, I'm guessing the issue lies with the part that has this:
CopyPath = ThisWorkbook.Worksheets("LeaveReport").Range("C" & CopyPathRow)
and is "supposed" to update in the For loop via this:
CopyPathRow = CopyPathRow + 1
Move the line
CopyPath = ThisWorkbook.Worksheets("LeaveReport").Range("C" & CopyPathRow)
Inside the loop, that value of CopyPath is never being changed, but the value of CopyPathRow is.
Edit: I wouldn't call this recursion either.