Get sub-folders name with files name by VBA - vba

I want to get subfolders name with files name through Excel VBA.
What I really want is Column A shows subfolders name, Column B shows files name.
Here is my code:
Option Explicit
Private xRow As Long
Sub Get_MAIN_File_Names()
Dim fso As FileSystemObject
Dim xDirect As String
Dim xRootFolder As Folder
Dim DrawingNumb As String
Dim RevNumb As String
Dim rootFolderStr As String
Set fso = New FileSystemObject
xRow = 0
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Main File"
.Show
'PROCESS ROOT FOLDER
If .SelectedItems.Count <> 0 Then
xDirect = .SelectedItems(1) & "\"
Set xRootFolder = fso.GetFolder(xDirect)
ProcessFolder fso, xRootFolder
End If
End With
End Sub
Private Sub ProcessFolder(fso As FileSystemObject, xFolder As Folder)
Dim xFiles As Files
Dim xFile As File
Dim xSubFolders As Folders
Dim xSubFolder As Folder
Dim xSubFolderName As String
Dim xFileName As String
Dim xFileTime As String
Set xFiles = xFolder.Files
'Adding Column names
Cells(1, "A").Value = "SubFolder Name"
Cells(1, "B").Value = "File Name"
Cells(1, "C").Value = "Modified Date/Time"
For Each xSubFolder In xSubFolders
xSubFolderName = xSubFolder.Name
ActiveCell.Offset(xRow, 0) = xSubFolderName
xRow = xRow + 1
Next xSubFolder
'LOOPS THROUGH EACH FILE NAME IN FOLDER
For Each xFile In xFiles
'EXTRACT INFORMATION FROM FILE NAME
xFileName = xFile.Name
xFileTime = xFile.DateLastModified
'INSERT INFO INTO EXCEL
ActiveCell.Offset(xRow, 1) = xFileName
ActiveCell.Offset(xRow, 2) = xFileTime
xRow = xRow + 1
Next xFile
Set xSubFolders = xFolder.SubFolders
For Each xSubFolder In xSubFolders
ProcessFolder fso, xSubFolder
Next xSubFolder
End Sub
However, I don't get what I want. I think the problem is here:
For Each xSubFolder In xSubFolders
xSubFolderName = xSubFolder.Name
ActiveCell.Offset(xRow, 0) = xSubFolderName
xRow = xRow + 1
Next xSubFolder
Which part do I ignore? Or is there another way to solve?
I think the code is too long. Maybe inefficient. How to modify the code?

Your entire
For Each xSubFolder In xSubFolders
xSubFolderName = xSubFolder.Name
ActiveCell.Offset(xRow, 0) = xSubFolderName
xRow = xRow + 1
Next xSubFolder
section is going to fail because you haven't defined xSubFolders at that point. Even if it didn't fail, it wouldn't do what you wanted because it would be moving the writing of the subfolder name away from the rows where you are writing the file details.
To resolve your issue you should delete that section and simply write the folder name out at the same time as you write the file details:
Private Sub ProcessFolder(fso As FileSystemObject, xFolder As Folder)
Dim xFiles As Files
Dim xFile As File
Dim xSubFolders As Folders
Dim xSubFolder As Folder
Dim xFileName As String
Dim xFileTime As String
Set xFiles = xFolder.Files
Set xSubFolders = xFolder.SubFolders
'Adding Column names
'This should really be done once in the main procedure, rather than being performed
'for every folder processed, but is simply overwriting the information written
'last time through so will be inefficient but not incorrect.
Cells(1, "A").Value = "SubFolder Name"
Cells(1, "B").Value = "File Name"
Cells(1, "C").Value = "Modified Date/Time"
'LOOPS THROUGH EACH FILE NAME IN FOLDER
For Each xFile In xFiles
'EXTRACT INFORMATION FROM FILE NAME
xFileName = xFile.Name
xFileTime = xFile.DateLastModified
'INSERT INFO INTO EXCEL
ActiveCell.Offset(xRow, 0) = xFolder.Name
ActiveCell.Offset(xRow, 1) = xFileName
ActiveCell.Offset(xRow, 2) = xFileTime
xRow = xRow + 1
Next xFile
Set xSubFolders = xFolder.SubFolders
For Each xSubFolder In xSubFolders
ProcessFolder fso, xSubFolder
Next xSubFolder
End Sub

Try this version.
Sub TestListFolders()
Application.ScreenUpdating = False
'create a new workbook for the folder list
'commented out by dr
'Workbooks.Add
'line added by dr to clear old data
Cells.Delete
' add headers
With Range("A1")
.Formula = "Folder contents:"
.Font.Bold = True
.Font.Size = 12
End With
Range("A3").Formula = "Folder Path:"
Range("B3").Formula = "Folder Name:"
Range("C3").Formula = "Size:"
Range("D3").Formula = "Subfolders:"
Range("E3").Formula = "Files:"
Range("F3").Formula = "Short Name:"
Range("G3").Formula = "Short Path:"
Range("A3:G3").Font.Bold = True
'ENTER START FOLDER HERE
' and include subfolders (true/false)
ListFolders "C:\Users\Excel\Desktop\Coding\Microsoft Excel\Work Samples\Finance\", True
Application.ScreenUpdating = True
End Sub
Sub ListFolders(SourceFolderName As String, IncludeSubfolders As Boolean)
' lists information about the folders in SourceFolder
' example: ListFolders "C:\", True
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.Folder, SubFolder As Scripting.Folder
Dim r As Long
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
'line added by dr for repeated "Permission Denied" errors
On Error Resume Next
' display folder properties
r = Range("A65536").End(xlUp).Row + 1
Cells(r, 1).Formula = SourceFolder.Path
Cells(r, 2).Formula = SourceFolder.Name
Cells(r, 3).Formula = SourceFolder.Size
Cells(r, 4).Formula = SourceFolder.SubFolders.Count
Cells(r, 5).Formula = SourceFolder.Files.Count
Cells(r, 6).Formula = SourceFolder.ShortName
Cells(r, 7).Formula = SourceFolder.ShortPath
If IncludeSubfolders Then
For Each SubFolder In SourceFolder.SubFolders
ListFolders SubFolder.Path, True
Next SubFolder
Set SubFolder = Nothing
End If
Columns("A:G").AutoFit
Set SourceFolder = Nothing
Set FSO = Nothing
'commented out by dr
'ActiveWorkbook.Saved = True
End Sub
As an alternative, you can download the sample file from the link below (click 'Download Now'). That Macro will do a nice job for you.
http://learnexcelmacro.com/wp/2011/11/how-to-get-list-of-all-files-in-a-folder-and-sub-folders/

The code you provided is unlikely to work for a number of reasons, have a look at the changes below, which might help:
Private Sub ProcessFolder(FSO as FileSystemObject, xFolder As Folder)
Dim xFile as File
Dim CurRow As Integer
'Your original code was going to wipe over the data when you got to each new SubFolder. This should prevent that:
For CurRow = 1 to 100000
If Range("A" & CurRow).Value = "" And Range("B" & CurRow).Value = "" Then Exit For
Next CurRow
If CurRow = 1 then
Range("A1").Value = "Sub Folder Name"
Range("B1").Value = "File Name"
Range("C1").Value = "Modified Date/Time"
CurRow = CurRow + 1
End If
Range("A" & CurRow).Value = xFolder.Name
CurRow = CurRow + 1
For Each xFile in xFolder.Files
Range("B" & CurRow).Value = xFile.Name
Range("C" & CurRow).Value = xFile.DateLastModified
CurRow = CurRow + 1
Next xFile
End Sub

Related

Improving combine txt code through VBA

I have below VBA code that divided for tWo. First part of the code collect data from file directory and paste it on excel file (file name, path & modified date).
Second part of the code collect all txt file in the folder and marge them to one list in the same sheet.
I tried to improve my code to support more than one folder source and to combine both codes to one ( I joined two different codes to one) but I failed to do it. Any idea how to modified it?
Thanks,
Code:
Sub list()
'adding file name, path & last modify date
Dim FSO As Scripting.FileSystemObject
Dim FileItem As Scripting.File
SourceFolderName = "\\HA04HUCM0002\TestLog\LOT\avi_tests"
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
Range("c2:e2") = Array("text file", "path", "Date Last Modified")
i = 3
For Each FileItem In SourceFolder.Files
Cells(i, 3) = FileItem.Name
Cells(i, 4) = FileItem
Cells(i, 5) = FileItem.DateLastModified
i = i + 1
Next FileItem
Set FSO = Nothing
'combain txt data into one sheet
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Kutools for Excel]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet
If MsgBox("Clear the existing sheet before importing?", vbYesNo, "Kutools for Excel") = vbYes Then xSht.UsedRange.Clear
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "" & "*.txt")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "" & xFile)
Columns(1).Insert xlShiftToRight
Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
ActiveSheet.UsedRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
xWb.Close False
xFile = Dir
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "no txt files ", , "Kutools for Excel"
End Sub
To process another folder, simply ask the User if they want to run the code again.
Application.ScreenUpdating = True
If MsgBox("Do you want to process another folder?", vbYesNoCancel, "Kutools for Excel") = vbYes Then
Call list
End If

VBA to find word documents and specified words in content and then list in excel

I have multiple word documents in a folder.
What I really want is to list the document names and check whether these docs incude some specified words.
I create two word documents for example to explain.
There are two documents, Doc A and Doc B, in a folder.
I want to list the file name Doc A and Doc B in the excel column A.
After listing the doc name in column A, I want to check whether specified words "classification" and "Statistics" are in the docs.
If these specified words in the document, it will mark in the excel. Please see below picture for the result I want.
I provide the code in the following:
Option Explicit
Private xRow As Long
Sub Get_MAIN_File_Names()
Dim fso As FileSystemObject
Dim xDirect As String
Dim xRootFolder As Folder
Dim DrawingNumb As String
Dim RevNumb As String
Dim rootFolderStr As String
Set fso = New FileSystemObject
xRow = 0
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Main File"
.Show
'PROCESS ROOT FOLDER
If .SelectedItems.Count <> 0 Then
xDirect = .SelectedItems(1) & "\"
Set xRootFolder = fso.GetFolder(xDirect)
ProcessFolder fso, xRootFolder
End If
End With
End Sub
Private Sub ProcessFolder(fso As FileSystemObject, xFolder As Folder)
Dim xFiles As Files
Dim xFile As File
Dim xSubFolders As Folders
Dim xSubFolder As Folder
Dim xFileName As String
Dim objWordApplication As New Word.Application
Dim objWordDocument As Word.Document
Dim strFile As String
strFile = Dir(xFolder & "*.doc", vbNormal)
While strFile <> ""
With objWordApplication
Set objWordDocument = .Documents.Open(FileName:=xFolder & strFile, AddToRecentFiles:=False, ReadOnly:=True, Visible:=False)
Set xFiles = xFolder.Files
'Adding Column names
Cells(1, "A").Value = "Document Name"
Cells(1, "B").Value = "classification"
Cells(1, "C").Value = "Statistics"
'LOOPS THROUGH EACH FILE NAME IN FOLDER
For Each xFile In xFiles
'EXTRACT INFORMATION FROM FILE NAME, this part may not add
xFileName = xFile.Name
Set Docs = objWordDocument.Content
With Docs.Find
.ClearFormatting
.Text = "classification"
Wrap:=wdFindContinue
End With
With Docs.Find
.ClearFormatting
.Text = "Statistics"
Wrap:=wdFindContinue
End With
'INSERT INFO INTO EXCEL
ActiveCell.Offset(xRow, 0) = xFileName
'Below needs to add.
ActiveCell.Offset(xRow, 1) =
ActiveCell.Offset(xRow, 2) =
'Above needs to add.
xRow = xRow + 1
With objWordDocument
.Close
End With
Next xFile
Set xSubFolders = xFolder.SubFolders
For Each xSubFolder In xSubFolders
ProcessFolder fso, xSubFolder
Next xSubFolder
End Sub
Based on above code, it fails.
I think the problem is With Docs.Find.....; however, I'm not really sure about it.
Moreover, I do not know how to do this part.
'Below needs to add.
ActiveCell.Offset(xRow, 1) =
ActiveCell.Offset(xRow, 2) =
'Above needs to add.
Can any one help me edit the code?
Maybe this code will help you out, it does:
Assume you got a activesheet setup with the three headers there
Loop through .docx files in specified folder
Checks wordrange for specified tekst
Returns true or false and puts found or not found in appropriate cell
Sub LoopWordDocs()
Dim FLDR As String
Dim wDoc As Word.Document
Dim wRNG As Word.Range
Dim LR As Long, COL As Long
Dim WS As String
Dim wAPP As Word.Application
Dim WordWasNotRunning As Boolean
On Error Resume Next
Set wAPP = GetObject(, "Word.Application")
If Err Then
Set wAPP = New Word.Application
WordWasNotRunning = True
End If
On Error GoTo Err_Handler
WS = ThisWorkbook.ActiveSheet.Name
FLDR = "U:\Test\" 'Change directory accordingly
aDoc = Dir(FLDR & "*.docx") 'Change docx to .doc if you need
Do While aDoc <> ""
Set wDoc = Documents.Open(Filename:=FLDR & aDoc)
LR = Sheets(WS).Cells(Rows.Count, "A").End(xlUp).Row + 1
Sheets(WS).Cells(LR, 1) = aDoc
Set wRNG = wDoc.Range
For COL = 2 To 3 'It will loop through B1 and C1 to check if present in text
With wRNG.Find
.Text = Sheets(WS).Cells(1, COL).Text
.MatchCase = False
.MatchWholeWord = True
If wRNG.Find.Execute = True Then
Sheets(WS).Cells(LR, COL) = "V" 'Change V to your liking
Else
Sheets(WS).Cells(LR, COL) = "X" 'Change X to your liking
End If
End With
Next COL
wDoc.Close SaveChanges:=True
aDoc = Dir
Loop
Exit Sub
Err_Handler:
MsgBox "Word caused a problem. " & Err.Description, vbCritical, "Error: " & Err.Number
If WordWasNotRunning Then
wAPP.Quit
End If
End Sub
Note: You'll have to turn on Microsoft Word 14.0 Object Library for this to work

VBA: Cycle through files in a folder, and take information from all that contain a certain string

I've been trying to write a code for VBA that will cycle through a folder, given a user inputted folder path, and paste some information, like a range of cells, and the file name in my work book based on whether or not a filename contains a specific string.
Currently I have a code that will take a folder path inputted in cell 1,1 in excel, but it will return all filenames, not just filenames containing "abc" for example. It's been a while since I used VBA, and this is my way of coming back to it.
Sub getFile()
Dim MyFolder As String
Dim file As String
MyFolder = Cells(1, 1)
file = Dir(MyFolder & ".xl??")
Dim col As Integer
col = 2
Do While file <> ""
Cells(3, col) = file
col = col + 1
file = Dir()
Loop
End Sub
My problem is that I haven't been able to find a way to incorporate an "If" to say only use files that contain the string "abc"
Thanks everybody!
Try using
file = Dir(MyFolder & "*abc*.xl??")
instead of
file = Dir(MyFolder & ".xl??")
Just to close this post and in order not to have another open question (with the answer being in a comment) I re-post my comment here as a solution.
I do not think you have made yourself clear, but I believe you want to loop through file that contain "abc" in their name, is it correct?!
If so, use asterisks in Dir function when declaring variable "file", like this:
file = Dir(MyFolder & "*abc*.xl*")
Here is a great sample that will do everything you want and a lot more, if you just modify the code a bit....
http://www.learnexcelmacro.com/wp/2011/11/how-to-get-list-of-all-files-in-a-folder-and-sub-folders/
Download the sample file from the link named 'Download Now'.
Sub GetFilesInFolder(SourceFolderName As String)
'--- For Example:Folder Name= "D:\Folder Name\"
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.folder, SubFolder As Scripting.folder
Dim FileItem As Scripting.File
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
'--- This is for displaying, whereever you want can be configured
r = 14
For Each FileItem In SourceFolder.Files
Cells(r, 2).Formula = r - 13
Cells(r, 3).Formula = FileItem.Name
Cells(r, 4).Formula = FileItem.Path
Cells(r, 5).Formula = FileItem.Size
Cells(r, 6).Formula = FileItem.Type
Cells(r, 7).Formula = FileItem.DateLastModified
Cells(r, 8).Formula = "=HYPERLINK(""" & FileItem.Path & """,""" & "Click Here to Open" & """)"
r = r + 1 ' next row number
Next FileItem
Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub
Sub GetFilesInFolder(SourceFolderName As String, Subfolders As Boolean)
'--- For Example:Folder Name= "D:\Folder Name\" and Flag as Yes or No
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.folder, SubFolder As Scripting.folder
Dim FileItem As Scripting.File
'Dim r As Long
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
'--- This is for displaying, whereever you want can be configured
r = 14
For Each FileItem In SourceFolder.Files
Cells(r, 2).Formula = r - 13
Cells(r, 3).Formula = FileItem.Name
Cells(r, 4).Formula = FileItem.Path
Cells(r, 5).Formula = FileItem.Size
Cells(r, 6).Formula = FileItem.Type
Cells(r, 7).Formula = FileItem.DateLastModified
Cells(r, 8).Formula = "=HYPERLINK(""" & FileItem.Path & """,""" & "Click Here to Open" & """)"
r = r + 1 ' next row number
Next FileItem
'--- This is the Function to go each and Every Folder and get the Files. This is a Nested-Function Calling.
If Subfolders = True Then
For Each SubFolder In SourceFolder.Subfolders
ListFilesInFolder SubFolder.Path, True
Next SubFolder
End If
Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub

VBA-List various filenames from folders and subfolders based on different strings

I am trying to list all the files from a folder and subfolder(s) based on a string from a userform into a new workbook. For eg. I am want to input the string as 0200-T1;0201-T12 and I am splitting the string using ";" to search for two or more files which begin with the respective strings. Please have a look at my code and suggest corrections. Currently it only lists the first string from the split array.
Sub ListFilesHomolog()
xdir = Usrfrm_JbOrderFiles.Txtbx_Browse2.Value ' define search path
Set mywb = Workbooks.Add
Call ListFilesInFolderHomolog(xdir, True)
End Sub
Sub ListFilesInFolderHomolog(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
Dim xFileSystemObject As Object
Dim xFolder As Object
Dim xSubFolder As Object
Dim xFile As Object
Dim rowIndex As Long
Application.ScreenUpdating = False
Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set xFolder = xFileSystemObject.GetFolder(xFolderName)
On Error GoTo 0
rowIndex = Application.ActiveSheet.Range("A1048576").End(xlUp).Row + 1
For Each xFile In xFolder.Files
On Error Resume Next
fname = xFile.Name
HomFiles = Split(Usrfrm_JbOrderFiles.txtbx_jbOrdNo2.Value, ";")
For scount = LBound(HomFiles) To UBound(HomFiles)
srchTrm = HomFiles(scount) 'value from form
tst = Split(fname, "-")
If InStr(UCase(tst(0) & "-" & tst(1)), UCase(srchTrm)) = 0 Then GoTo a: 'skip if string not found
With mywb
mywb.Activate
Worksheets(1).Columns("A:H").FormatConditions.Add Type:=xlExpression, Formula1:="=E($A1<>"""";MOD(LIN();2))"
Worksheets(1).Columns("A:H").FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Worksheets(1).Columns("A:H").FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -4.99893185216834E-02
End With
Worksheets(1).Columns("A:H").FormatConditions(1).StopIfTrue = False
Worksheets(1).Cells(1, 1).Value = "File Name" 'file name"
Worksheets(1).Cells(1, 8).Value = "Link" 'file name"
Worksheets(1).Cells(rowIndex, 1).Formula = xFile.Name 'file name
ActiveSheet.Hyperlinks.Add Cells(rowIndex, 8), xFile, TextToDisplay:="Open"
Worksheets(1).Cells.EntireColumn.AutoFit
ActiveWindow.DisplayGridlines = False
ActiveWindow.DisplayHeadings = False
End With
rowIndex = rowIndex + 1
Next scount
a:
Next xFile
If xIsSubfolders Then
For Each xSubFolder In xFolder.SubFolders
ListFilesInFolderHomolog xSubFolder.Path, True
Next xSubFolder
End If
Set xFile = Nothing
Set xFolder = Nothing
Set xFileSystemObject = Nothing
Application.ScreenUpdating = True
End Sub
You currently exit from your For scount loop if the file being looked at does not match the first criteria.
Using your example criteria of "0200-T1;0201-T12", if the filename does not contain the string "0200-T1" you exit the loop and never check to see if the filename contains the string "0201-T12".
You need to change
Next scount
a:
Next xFile
to be
a:
Next scount
Next xFile

Excel VBA: Create list of subfolders and files within source folder

I am using the following code to list all files in a host folder and it's sub folders. The code works great but, do you know how I can update the code to also list some the file attributes.
Sub file_list()
Call ListFilesInFolder("W:\ISO 9001\INTEGRATED_PLANNING\", True)
End Sub
Sub ListFilesInFolder(ByVal SourceFolderName As String, ByVal IncludeSubfolders As Boolean)
Dim FSO As Object
Dim SourceFolder As Object
Dim SubFolder As Object
Dim FileItem As Object
Dim r As Long
Set FSO = CreateObject("Scripting.FileSystemObject")
Set SourceFolder = FSO.getFolder(SourceFolderName)
r = Range("A65536").End(xlUp).Row + 1
For Each FileItem In SourceFolder.Files
Cells(r, 1).Formula = FileItem.Name
r = r + 1
X = SourceFolder.Path
Next FileItem
If IncludeSubfolders Then
For Each SubFolder In SourceFolder.Subfolders
ListFilesInFolder SubFolder.Path, True
Next SubFolder
End If
Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub
Function GetFileOwner(ByVal FilePath As String, ByVal FileName As String)
Dim objFolder As Object
Dim objFolderItem As Object
Dim objShell As Object
FileName = StrConv(FileName, vbUnicode)
FilePath = StrConv(FilePath, vbUnicode)
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(StrConv(FilePath, vbFromUnicode))
If Not objFolder Is Nothing Then
Set objFolderItem = objFolder.ParseName(StrConv(FileName, vbFromUnicode))
End If
If Not objFolderItem Is Nothing Then
GetFileOwner = objFolder.GetDetailsOf(objFolderItem, 8)
Else
GetFileOwner = ""
End If
Set objShell = Nothing
Set objFolder = Nothing
Set objFolderItem = Nothing
End Function
What I would really like to see is;
Column A = Host folder/subfolder
Column B = File name
Column C = hyperlink to file
Is this possible?
I do have a code that created hyperlinks but, I do not know how to add to the existing code.
Sub startIt()
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "W:\ISO 9001\INTEGRATED_PLANNING\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
End Sub
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.Subfolders
DoFolder SubFolder
Next
i = Cells(Rows.Count, 1).End(xlUp).Row + 1
Dim File
For Each File In Folder.Files
ActiveSheet.Hyperlinks.Add Anchor:=Cells(i, 1), Address:= _
File.Path, TextToDisplay:=File.Name
i = i + 1
Next
End Sub
You can see the list of properties that the File Object supports here: https://msdn.microsoft.com/en-us/library/1ft05taf(v=vs.84).aspx
So you can enhance your code, where it is taking the .Name property and putting that in a cell formula, to do something similar with other properties, such as the .Type of the file.
For Each FileItem In SourceFolder.Files
Cells(r, 1).Formula = FileItem.Name
Cells(r, 2).Value = FileItem.Type
ActiveSheet.Hyperlinks.Add Anchor:=Cells(r, 3), Address:= _
FileItem.Path, TextToDisplay:=FileItem.Name
r = r + 1
X = SourceFolder.Path
Next FileItem
n.b. I've used Value instead of Formula, but in this case the result will be the same.
In a similar manner, you can add another Cells(r, 3).Value = line to set the value of cell in the current row r and column 3 to whatever your hyperlink is.
I wrote a little script for this purpose to my colleague for a time ago...
See my code below:
Sub FolderNames()
'Written by Daniel Elmnas Last update 2016-02-17
Application.ScreenUpdating = False
Dim xPath As String
Dim xWs As Worksheet
Dim fso As Object, j As Long, folder1 As Object
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Choose the folder"
.Show
End With
On Error Resume Next
xPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"
Application.Workbooks.Add
Set xWs = Application.ActiveSheet
xWs.Cells(1, 1).Value = xPath
xWs.Cells(2, 1).Resize(1, 5).Value = Array("Subfolder", "Hostfolder", "Filename", "Date Created", "Date Last Modified")
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder1 = fso.getFolder(xPath)
getSubFolder folder1
xWs.Cells(2, 1).Resize(1, 5).Interior.Color = 65535
xWs.Cells(2, 1).Resize(1, 5).EntireColumn.AutoFit
Application.ScreenUpdating = True
End Sub
Sub getSubFolder(ByRef prntfld As Object)
Dim SubFolder As Object
Dim subfld As Object
Dim xRow As Long
For Each SubFolder In prntfld.SubFolders
xRow = Range("A1").End(xlDown).Row + 1
Cells(xRow, 1).Resize(1, 5).Value = Array(SubFolder.Path, Left(SubFolder.Path, InStrRev(SubFolder.Path, "\")), SubFolder.Name, SubFolder.DateCreated, SubFolder.DateLastModified)
Next SubFolder
For Each subfld In prntfld.SubFolders
getSubFolder subfld
Next subfld
End Sub
Here is the result:
You can modify it a bit though.
If you example dont want to use a window-dialog and instead use
"W:\ISO 9001\INTEGRATED_PLANNING\"
Cheers!