Insert Images into Excel from sub directories based on cell value - excel

I am a VBA novice but have been able to modify the below code to insert images in my spreadsheet based on cell values as long as the images are in the specific folder. How would I go about changing the code so that it searches all the sub folders within the directory? Any help would be greatly appreciated.
Public Sub Add_Pics_Example()
Dim oCell As Range
Dim oRange As Range
Dim oActive As Worksheet
Dim sPath As String
Dim sFile As String
Dim oShape As Shape
Worksheets("Range").Activate
sPath = "Z:\Pictures\Product Images\"
ActiveSheet.DrawingObjects.Select
Selection.Delete
Set oActive = ActiveSheet
Set oRange = oActive.Range("B4:bz4")
On Error Resume Next
For Each oCell In oRange
sFile = oCell.Value & ".jpg"
Set oShape = oActive.Shapes.AddPicture(sPath & sFile, False, True, _
oCell.Offset(-3, 0).Left + 30, oCell.Offset(-3, 0).Top + 3, 60, 60)
Next oCell
On Error GoTo 0
Application.ScreenUpdating = True
End Sub

Untested but should be pretty close:
Public Sub Add_Pics_Example()
Dim oCell As Range
Dim oRange As Range
Dim wsActive As Worksheet
Dim sFile As String
Dim dictFiles As Object
Set wsActive = Worksheets("Range")
wsActive.DrawingObjects.Delete
'get all the image files first
Set dictFiles = AllFilesbyName("Z:\Pictures\Product Images\", "*.jpg")
For Each oCell In wsActive.Range("B4:BZ4")
sFile = oCell.Value & ".jpg"
'do we have this file ?
If dictFiles.exists(sFile) Then
wsActive.Shapes.AddPicture dictFiles(sFile), False, True, _
oCell.Offset(-3, 0).Left + 30, _
oCell.Offset(-3, 0).Top + 3, 60, 60
End If
Next oCell
End Sub
'starting at startFolder, return a dictionary mapping file names to
' full paths (note doesn't handle >1 file of the same name)
' from startfolder and all subfolders
Function AllFilesbyName(startFolder As String, filePattern As String, _
Optional subFolders As Boolean = True) As Object
Dim fso, fldr, f, subFldr
Dim dictFiles As Object, colSub As New Collection
Set fso = CreateObject("scripting.filesystemobject")
Set dictFiles = CreateObject("scripting.dictionary")
dictFiles.comparemode = 1 'TextCompare: case-insensitive
colSub.Add startFolder
Do While colSub.Count > 0
Set fldr = fso.getfolder(colSub(1))
colSub.Remove 1
For Each f In fldr.Files
If UCase(f.Name) Like UCase(filePattern) Then
'EDIT: fixed the line below
dictFiles(f.Name) = fso.buildpath(fldr.Path, f.Name)
End If
Next f
If subFolders Then
For Each subFldr In fldr.subFolders
colSub.Add subFldr.Path
Next subFldr
End If
Loop
Set AllFilesbyName = dictFiles
End Function

Related

Create folders and subfolder and sub text files from excel sheet

hi i'm trying to create a list of folders from an excel sheet and in each folder, it should be a txt file named let's say name.txt and in each of these files it should write wats in column b
pic1
I used this code to create the folders but I need help about creating the txt files
Sub MakeFolders()
Dim Rng As Range
Dim maxRows, maxCols, r, c As Integer
Set Rng = Selection
maxRows = Rng.Rows.Count
maxCols = Rng.Columns.Count
For c = 1 To maxCols
r = 1
Do While r <= maxRows
If Len(Dir(ActiveWorkbook.Path & "\" & Rng(r, c), vbDirectory)) = 0 Then
MkDir (ActiveWorkbook.Path & "\" & Rng(r, c))
On Error Resume Next
End If
r = r + 1
Loop
Next c
End Sub
I need help generating the text file in each folder
Create Text Files From Worksheet Data
Sub MakeFolders()
Const fRow As Long = 2
Const SubFolderColumn As String = "A"
Const TextColumn As String = "B"
Const TextFileNameCellAddress As String = "B1"
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim wbPath As String: wbPath = ws.Parent.Path & "\"
Dim TextFileName As String
TextFileName = CStr(ws.Range(TextFileNameCellAddress).Value)
Dim lRow As Long
lRow = ws.Cells(ws.Rows.Count, SubFolderColumn).End(xlUp).Row
Dim srg As Range: Set srg = ws.Range(ws.Cells(fRow, SubFolderColumn), _
ws.Cells(lRow, SubFolderColumn))
Dim sCell As Range
Dim TextFile As Long
Dim FolderPath As String
Dim SubFolderName As String
Dim FilePath As String
Dim FileText As String
For Each sCell In srg.Cells
SubFolderName = CStr(sCell.Value)
If Len(SubFolderName) > 0 Then
FolderPath = wbPath & SubFolderName & "\"
If Len(Dir(FolderPath, vbDirectory)) = 0 Then
MkDir FolderPath
End If
FilePath = FolderPath & TextFileName
FileText = CStr(sCell.EntireRow.Columns(TextColumn).Value)
' Or (the same):
'FileText = CStr(ws.Cells(sCell.Row, TextColumn).Value)
TextFile = FreeFile
Open FilePath For Output As #TextFile
Print #TextFile, FileText
Close TextFile
End If
Next sCell
MsgBox "Files created.", vbInformation
End Sub
try to use FSO.CreateTextFile:
Sub Macro1()
'
' Macro1 Macro
'
'
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim strPath As String
strPath = "d:\name.txt"
Dim oFile As Object
Set oFile = fso.CreateTextFile(strPath)
oFile.WriteLine "test"
oFile.Close
Set fso = Nothing
Set oFile = Nothing
End Sub

Find String and extract in vba using fso

so my code currently goes through a folder and extracts Ranges of data from every file in the folder into a format set by me, it also extracts the filename.
Now i need to use fso to search for certain string inside the file not the filename, lets say "Smart", and in the file "Smart" appears quite a few times, but i only want to extract it once.
Thank you so much to anyone who is able to provide me the small part of the code or some advices to help me continue on!
Option Explicit
Sub ScanFiles()
Application.ScreenUpdating = False
Dim wks As Worksheet
Set wks = Worksheets.Add
' New worksheet for question 2
Dim wksFSO As Worksheet
' Add headers data
With wks
.Range("A1:E1") = Array("Test", "Temp", "Start", "Type", "FileName", "Test", "EndDate", "Smart", "Er")
End With
' Set your copy ranges
Dim CopyRange(1 To 4) As String
CopyRange(1) = "A18"
CopyRange(2) = "A19"
CopyRange(3) = "A14"
CopyRange(4) = "A19"
' Early Binding - Add "Microsoft Scripting Runtime" Reference
Dim FSO As New Scripting.FileSystemObject
' Set FolderPath
Dim FolderPath As String
FolderPath = "c:\Users\Desktop\Tryout\"
' Set Folder FSO
Dim Folder As Scripting.Folder
Set Folder = FSO.GetFolder(FolderPath)
' Loop thru each file -> Assuming only 6 files
Dim File As Scripting.File
For Each File In Folder.Files
' If loop looking for specific files and copy to new FSOWorksheet
If File.Name Like "ReportFile" Then
wksFSO.Cells(1, 1) = File.Name
End If
Dim wkbData As Workbook
Set wkbData = Workbooks.Open(File.Path)
Dim wksData As Worksheet
ActiveSheet.Name = "Sheet1"
Set wksData = wkbData.Worksheets("Sheet1") ' -> Assume this file has only 1 worksheet
Dim BlankRow As Long
BlankRow = wks.Range("A" & wks.Rows.Count).End(xlUp).Row + 1
Dim i As Long
For i = 1 To 4
wks.Cells(BlankRow, i).Value = wksData.Range(CopyRange(i)).Value
Next i
' Write filename in col E
wks.Cells(BlankRow, 5).Value = File.Name
wkbData.Close False
Next File
Range("A:I").EntireColumn.AutoFit
Application.ScreenUpdating = True
End Sub
This could help you, what it does is it search through the path's folders and each excel file that is inside it for the word that you are going to put in the input box.
Sub SearchFolders()
Dim fso As Object
Dim fld As Object
Dim strSearch As String
Dim strPath As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
'Change as desired
strPath = "c:\MyFolder"
'You can enter your smart word here
strSearch = inputbox("Please enter a word to be searched.","Search for a word")
Set wOut = Worksheets.Add
lRow = 1
With wOut
.Cells(lRow, 1) = "Workbook"
.Cells(lRow, 2) = "Worksheet"
.Cells(lRow, 3) = "Cell"
.Cells(lRow, 4) = "Text in Cell"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(strPath)
strFile = Dir(strPath & "\*.xls*")
Do While strFile <> ""
Set wbk = Workbooks.Open _
(Filename:=strPath & "\" & strFile, _
UpdateLinks:=0, _
ReadOnly:=True, _
AddToMRU:=False)
For Each wks In wbk.Worksheets
Set rFound = wks.UsedRange.Find(strSearch)
If Not rFound Is Nothing Then
strFirstAddress = rFound.Address
End If
Do
If rFound Is Nothing Then
Exit Do
Else
lRow = lRow + 1
.Cells(lRow, 1) = wbk.Name
.Cells(lRow, 2) = wks.Name
.Cells(lRow, 3) = rFound.Address
.Cells(lRow, 4) = rFound.Value
End If
Set rFound = wks.Cells.FindNext(After:=rFound)
Loop While strFirstAddress <> rFound.Address
Next
wbk.Close (False)
strFile = Dir
Loop
.Columns("A:D").EntireColumn.AutoFit
End With
MsgBox "Done"
ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub

How to iterate through all sub-folders and their sub-sub-folders and so on using vba to check a folder if it exist?

I have below code to check if a folder exist on the predefined directory.
Option Explicit
Public xStatus As String
Sub Status()
Application.ScreenUpdating = False
Dim fso As Object
Dim folder As Object
Dim subfolders As Object
Dim subfolder1 As Object
Dim Rg As Range
Dim xCell As Range
Dim xTxt As String
xTxt = ActiveWindow.RangeSelection.Address
Set Rg = Application.InputBox("Please select city/cities to check production status!!! ", "Lmtools", xTxt, , , , , 8)
If Rg Is Nothing Then
MsgBox ("No cities selected!!!")
Exit Sub
End If
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("D:\")
Set subfolders = folder.subfolders
For Each xCell In Rg
If xCell.Value <> "" Then
For Each subfolder1 In subfolders
xStatus = subfolder1.path
If xStatus Like "*?\" & xCell.Value Then
Cells(xCell.Row, xCell.Column + 1).Value = "Completed"
Cells(xCell.Row, xCell.Column + 2).Value = xStatus
GoTo nextiteration
Else
Cells(xCell.Row, xCell.Column + 1).Value = "Ongoing"
End If
Next
End If
nextiteration:
Next
Application.ScreenUpdating = True
End Sub
It works fine but only checks the sub-folders of "D:\" and not beyond that.
My folder could be present anywhere (either inside the sub-folders or their sub-folders or alongside "D:\"'s sub-folders.
my concern is how to iterate through all the folders.
I creted this a while back. Basically i used this to rename file in folders and sub-folders,
Option Explicit
Sub VersionRename()
Dim SelectedFolder As FileDialog
Dim T_Str As String
Dim FSO As Object
Dim RenamingFolder As Object, SubFolder As Object
Dim T_Name As String
Set SelectedFolder = Application.FileDialog(msoFileDialogFolderPicker)
SelectedFolder.Title = "Select folder:"
SelectedFolder.ButtonName = "Select Folder"
If SelectedFolder.Show = -1 Then
T_Str = SelectedFolder.SelectedItems(1)
Else
'MsgBox "Cancelled by user.", vbInformation
Set SelectedFolder = Nothing
Exit Sub
End If
Set SelectedFolder = Nothing
Set FSO = CreateObject("Scripting.FileSystemObject")
Set RenamingFolder = FSO.GetFolder(T_Str)
File_Renamer RenamingFolder
For Each SubFolder In RenamingFolder.SubFolders
File_Renamer SubFolder
Next
Set SubFolder = Nothing
Set RenamingFolder = Nothing
Set FSO = Nothing
MsgBox "Process completed!", vbInformation, Title:="Renaming Files"
End Sub
Private Sub File_Renamer(Folder As Object)
Dim File As Object
Dim T_Str As String
Dim T_Name As String
Dim PreVersionID As Variant
Dim NextVersionID As Variant
Dim StringReplace As String
PreVersionID = Application.InputBox("Input 1 if no version number otherwise input existing version number:", Type:=1)
If PreVersionID = False Then Exit Sub
NextVersionID = Application.InputBox("Input your next version number:", Type:=1)
If NextVersionID = False Then Exit Sub
T_Str = Format("_V" & NextVersionID)
For Each File In Folder.Files
T_Name = File.Name
'Debug.Print T_Name
If NextVersionID > 1 Then
StringReplace = Replace(T_Name, "_V" & PreVersionID, "", 1, 3)
'Debug.Print StringReplace
File.Name = Left(StringReplace, InStrRev(StringReplace, ".") - 1) & T_Str & Right(StringReplace, Len(StringReplace) - (InStrRev(StringReplace, ".") - 1))
Else
File.Name = Left(T_Name, InStrRev(T_Name, ".") - 1) & T_Str & Right(T_Name, Len(T_Name) - (InStrRev(T_Name, ".") - 1))
End If
Next
End Sub

Excel VBA Manual Transpose

The below code works until used on a directory with paths over 255 characters.
Runtime error 13 mismatch occurs.
I have a hunch that the built in .transpose operation does not support 255 characters.
How can I manually do this operation?
My other crawler is not recursive, so I have never had this issue.
At this point I'm wondering if recursive efficiency is worth it.
Also the UNC path output is a requirement, shortening it to drive letter is a not an option.
Option Explicit
Sub CreateFileStructureReport()
Dim Msheet As String
Dim minNum As Integer
Msheet = Application.ActiveWorkbook.Path
Application.Calculation = xlCalculationManual
Call GetFileList
Application.Calculation = xlCalculationAutomatic
Range("A2").Select
End Sub
Sub GetFileList()
Dim ans As String
Dim strFolder As String
Dim objFSO As Object
Dim objFolder As Object
Dim myResults As Variant
Dim lCount As Long
ans = Application.CommandBars("Web").Controls("Address:").Text
If ans = "" Then Exit Sub
ans = Left(ans, InStrRev(ans, "\"))
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(ans)
'the variable dimension has to be the second one
ReDim myResults(0 To 6, 0 To 0)
' place make some headers in the array
myResults(0, 0) = "Extension"
myResults(1, 0) = "Bytes"
myResults(2, 0) = "Created"
myResults(3, 0) = "Modified Info"
myResults(4, 0) = "Last Accessed"
myResults(5, 0) = "File Name"
myResults(6, 0) = "\\Root\T01\T02\T03\T04\T05\T06\T07\T08\T09\T10\T11\T12\T13\T14\T15\T16\T17\T18\T19\T20"
'Send the folder to the recursive function
FillFileList objFolder, myResults, lCount
' Dump these to a worksheet
DumpToWorksheet myResults
'tidy up
Set objFSO = Nothing
End Sub
Private Sub FillFileList(objFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)
Dim i As Integer
Dim objFile As Object
Dim fsoSubFolder As Object
Dim fsoSubFolders As Object
'load the array with all the files
For Each objFile In objFolder.Files
lCount = lCount + 1
ReDim Preserve myResults(0 To 6, 0 To lCount)
myResults(0, lCount) = objFile.Type
myResults(1, lCount) = objFile.Size
myResults(2, lCount) = objFile.DateCreated
myResults(3, lCount) = objFile.DateLastModified
myResults(4, lCount) = objFile.DateLastAccessed
myResults(5, lCount) = objFile.Name
myResults(6, lCount) = objFile.Path
Next objFile
'recursively call this function with any subfolders
Set fsoSubFolders = objFolder.SubFolders
DoEvents
For Each fsoSubFolder In fsoSubFolders
FillFileList fsoSubFolder, myResults, lCount
Next fsoSubFolder
End Sub
Private Sub DumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
Dim iSheetsInNew As Integer
Dim sh As Worksheet, wb As Workbook
Dim myColumnHeaders() As String
Dim l As Long, NoOfRows As Long
If mySh Is Nothing Then
'make a workbook if we didn't get a worksheet
iSheetsInNew = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1
Set wb = Application.Workbooks.Add
Application.SheetsInNewWorkbook = iSheetsInNew
Set sh = wb.Sheets(1)
Else
Set mySh = sh
End If
'since we switched the array dimensions, have to transpose
With sh
Range(.Cells(1, 1), .Cells(UBound(varData, 2) + 1, UBound(varData, 1) + 1)) = _
Application.WorksheetFunction.Transpose(varData)
.UsedRange.Columns.AutoFit
End With
Set sh = Nothing
Set wb = Nothing
End Sub

move subfolders based on date last modified

Trying to find MS Excel/VBA code to move all subfolders with lastdatemodified < date -30 to a different folder.
Like this (but obviously not this)
foldertomove = subfolder
folder = main
newfolder = archive
for each subfolder in main
if subfolder.datelastmodified < date - 30 then
move subfolder to archive
end if
next
Any help is greatly appreciated! Thanks!
Objective of this program is to Copy Folders, Sub-Folders and Folders
within Folders along with files contained in them. It could be any type of the file PDF, Text, Word, Excel etc.
This program will only copy Files which are 30 days older from
Current Time. User can adjust this date or between two dates as per
his requirements.
When program is run File Picker Dialog will open and allow user to
chose the folder to be archived.
It is very important that an Empty Directory Structure with same
folder structure as parent folder to be archived has is created.
Presently VBA code for this step has not been incorporated in this
program. Simplest way is to copy paste folder and then delete files
in various folders and sub-folders manually. It is one time exercise
so long as parent directory structure remains the same. Any changes
in the parent directory structure are also to be incorporated in the
Archive folder also.
Program will also output Directory and File Paths on a separate
workbook of the parent directory being archived. If it is not
required then relevant portions of the program can be commented out.
Snapshot of output is placed below.
Further improvements in this program shall be endeavoured based on feedback and help of experts.
Code is placed below.
Sub CopyFolders_Recursively()
Dim strFolder As String
Dim objFSO As Object
Dim objFolder As Object
Dim myResults As Variant
Dim lCount As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Get the directory from the user
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then Exit Sub
'user cancelled
strFolder = .SelectedItems(1)
End With
Set objFolder = objFSO.GetFolder(strFolder)
'the variable dimension has to be the second one
ReDim myResults(0 To 5, 0 To 0)
' place make some headers in the array
myResults(0, 0) = "Filename"
myResults(1, 0) = "Size"
myResults(2, 0) = "Created"
myResults(3, 0) = "Modified"
myResults(4, 0) = "Accessed"
myResults(5, 0) = "Full path"
'Send the folder to the recursive function
FillFileList objFolder, myResults, lCount
' Dump these to a worksheet
fcnDumpToWorksheet myResults
'tidy up
Set objFSO = Nothing
End Sub
Private Sub FillFileList(objFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)
Dim i As Integer
Dim objFile As Object
Dim fsoSubFolder As Object
Dim fsoSubFolders As Object
Dim ToPath As String
Dim lpath As String
ToPath = "C:\Archive\"
Dim Fdtdiff As Integer
'load the array with all the files
For Each objFile In objFolder.Files
lCount = lCount + 1
ReDim Preserve myResults(0 To 5, 0 To lCount)
myResults(0, lCount) = objFile.Name
myResults(1, lCount) = objFile.Size
myResults(2, lCount) = objFile.DateCreated
myResults(3, lCount) = objFile.DateLastModified
myResults(4, lCount) = objFile.DateLastAccessed
myResults(5, lCount) = objFile.Path
Fdtdiff = DateValue(Now) - DateValue(myResults(3, lCount))
If Fdtdiff > 30 Then
lpath = Replace(objFile.Path, "my_dir", "Archive")
objFile.Copy lpath
End If
Next objFile
'recursively call this function with any subfolders
Set fsoSubFolders = objFolder.SubFolders
For Each fsoSubFolder In fsoSubFolders
FillFileList fsoSubFolder, myResults, lCount
Next fsoSubFolder
End Sub
Private Sub fcnDumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
Dim iSheetsInNew As Integer
Dim sh As Worksheet, wb As Workbook
Dim myColumnHeaders() As String
Dim l As Long, NoOfRows As Long
If mySh Is Nothing Then
'make a workbook if we didn't get a worksheet
iSheetsInNew = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1
Set wb = Application.Workbooks.Add
Application.SheetsInNewWorkbook = iSheetsInNew
Set sh = wb.Sheets(1)
Else
Set mySh = sh
End If
'since we switched the array dimensions, have to transpose
With sh
Range(.Cells(1, 1), .Cells(UBound(varData, 2) + 1, UBound(varData, 1) + 1)) = _
Application.WorksheetFunction.Transpose(varData)
.UsedRange.Columns.AutoFit
End With
Set sh = Nothing
Set wb = Nothing
End Sub
Private Sub CopyFolders_Recursively()
Dim strFolder As String
Dim objFSO As Object
Dim objFolder As Object
Dim myResults As Variant
Dim lCount As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Get the directory from the user
'With Application.FileDialog(msoFileDialogFolderPicker)
'.Show
'If .SelectedItems.Count = 0 Then Exit Sub
'user cancelled
'strFolder = .SelectedItems(1)
'End With
strFolder = "D:\testing\" '<<change
Set objFolder = objFSO.GetFolder(strFolder)
'the variable dimension has to be the second one
ReDim myResults(0 To 5, 0 To 0)
' place make some headers in the array
myResults(0, 0) = "Filename"
myResults(1, 0) = "Size"
myResults(2, 0) = "Created"
myResults(3, 0) = "Modified"
myResults(4, 0) = "Accessed"
myResults(5, 0) = "Full path"
'Send the folder to the recursive function
FillFileList objFolder, myResults, lCount
' Dump these to a worksheet
fcnDumpToWorksheet myResults
CleanUpList
If Range("A2").Value = "" Then GoTo tidyup
AddFolders
Move_Folders
tidyup:
Cells.Delete
Range("A1").Select
'tidy up
Set objFSO = Nothing
End Sub
Private Sub FillFileList(objFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)
Dim i As Integer
Dim objFile As Object
Dim fsoSubFolder As Object
Dim fsoSubFolders As Object
Dim lpath As String
Dim Fdtdiff As Integer
'load the array with all the files
For Each objFile In objFolder.Files
If InStr(objFile.Path, "~Archive") = 0 Then 'don't get files from the archive folder (assumes the archive folder is a subfolder of the folder from which you're moving the other subfolders
lCount = lCount + 1
ReDim Preserve myResults(0 To 5, 0 To lCount)
myResults(0, lCount) = objFile.Name
myResults(1, lCount) = objFile.Size
myResults(2, lCount) = objFile.DateCreated
myResults(3, lCount) = objFile.DateLastModified
myResults(4, lCount) = objFile.DateLastAccessed
myResults(5, lCount) = objFile.Path
'Fdtdiff = DateValue(Now) - DateValue(myResults(3, lCount))
'If Fdtdiff > 30 Then
'lpath = Replace(objFile.Path, "my_dir", "~Archive")
'objFile.Copy lpath
'End If
End If
Next objFile
'recursively call this function with any subfolders
Set fsoSubFolders = objFolder.SubFolders
For Each fsoSubFolder In fsoSubFolders
FillFileList fsoSubFolder, myResults, lCount
Next fsoSubFolder
End Sub
Private Sub fcnDumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
'since we switched the array dimensions, have to transpose
With ThisWorkbook.Sheets(1) '<<change
Cells.ClearContents
Range(.Cells(1, 1), .Cells(UBound(varData, 2) + 1, UBound(varData, 1) + 1)) = _
Application.WorksheetFunction.Transpose(varData)
.UsedRange.Columns.AutoFit
End With
End Sub
Private Sub CleanUpList()
'sort most recent files to the top so when we remove dupes we'll be left with the most recent one
ThisWorkbook.Worksheets("Archive").Sort.SortFields.Clear '<<change sheet name
ThisWorkbook.Worksheets("Archive").Sort.SortFields.Add Key:=Range("D2:D65536") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ThisWorkbook.Worksheets("Archive").Sort
.SetRange Range("A1:F65536")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'remove parent folder from path we'll check later
Columns("F:F").Replace What:="D:\testing\", Replacement:="", LookAt:=xlPart, MatchCase:=False '<< Change
'remove file name, leaving just the folder we want to move
Columns("F:F").Replace What:="\*", Replacement:="", LookAt:=xlPart, MatchCase:=False
'we just need one!
ThisWorkbook.Sheets(1).Range("$A$1:$AZ$65536").RemoveDuplicates Columns:=6, Header:=xlYes '<< remove dupes of folders to move
Set Rng = Range("D1:D100") '<< change if you know it will be less or more than 100
For Each cell In Rng
If cell.Value <> "" Then
If cell.Value > Date - 30 Then '<<only keep it if more than 30 days (or whatever you want)
cell.Value = ""
End If
End If
Next
On Error Resume Next
Columns("D:D").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error GoTo 0
End Sub
Private Sub AddFolders() 'we'll archive by year within the archive subfolder
Set Rng = Range("D2:D100") '<< change if you know it will be less or more than 100
For Each x In Rng
If x.Value <> "" Then
On Error Resume Next
MkDir "D:\testing\~Archive\" & Format(x.Value - 30, "yyyy") '<< Change
On Error GoTo 0
End If
Next x
End Sub
Private Sub Move_Folders()
'This example move the folder from FromPath to ToPath
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Set Rng = Range("F2:F100") '<< change if you know it will be less or more than 100
For Each x In Rng
If x.Value <> "" Then
FromPath = "D:\testing\" & x.Value '<< Change
ToPath = "D:\testing\~Archive\" & Format(x.Offset(0, -2).Value - 30, "yyyy") & "\" & x.Value '<< Change
'Note: It is not possible to use a folder that exist in ToPath
'We created subfolders by year earlier so we can archive by year now
Set FSO = CreateObject("scripting.filesystemobject")
FSO.MoveFolder Source:=FromPath, Destination:=ToPath
End If
Next x
End Sub
Figured out a more direct way to get the subfolders needed to be archived:
Private Sub Archive_Hotel_Confs()
Sheets("Archiving").Select
Cells.ClearContents
Dim strStartPath As String
strStartPath = "W:testing\" 'ENTER YOUR START FOLDER HERE
ListHCFolder strStartPath
CleanUpList
If Range("A1").Value = "" Then GoTo tidyup
AddHCFolders
MoveHC_Folders
'tidy up
tidyup:
Cells.Delete
Range("A1").Select
Sheets("Last Run").Select
End Sub
Private Sub ListHCFolder(sFolderPath As String)
Dim FS As New FileSystemObject
Dim FSfolder As Folder
Dim subfolder As Folder
Dim i As Integer
Set FSfolder = FS.GetFolder(sFolderPath)
For Each subfolder In FSfolder.SubFolders
If InStr(subfolder.Name, "~Archive") = 0 Then
DoEvents
i = i + 1
'added this line
Cells(i, 1) = subfolder
Cells(i, 2) = subfolder.DateLastModified
'commented out this one
'Debug.Print subfolder
End If
Next subfolder
Set FSfolder = Nothing
End Sub
Private Sub CleanUpList()
Dim x As Variant
'remove parent folder from path we'll check later
Columns("A:A").Replace What:="W:testing\", Replacement:="", LookAt:=xlPart, MatchCase:=False '<< Change
Set Rng = Range(Range("B1"), Range("B" & Rows.Count).End(xlUp))
For Each x In Rng
If x.Value <> "" Then
If x.Value > Date - 30 Then '<<only keep it if more than 30 days (or whatever you want)
x.Value = ""
End If
End If
Next x
On Error Resume Next
Columns("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error GoTo 0
End Sub
Private Sub AddHCFolders() 'we'll archive by year within the archive subfolder
Dim x As Variant
Set Rng = Range(Range("B1"), Range("B" & Rows.Count).End(xlUp))
For Each x In Rng
If x.Value <> "" Then
On Error Resume Next
MkDir "W:testing\~Archive\" & Format(x.Value - 30, "yyyy") '<< Change
On Error GoTo 0
End If
Next x
End Sub
Private Sub MoveHC_Folders()
'This example move the folder from FromPath to ToPath
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim x As Variant
Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
For Each x In Rng
If x.Value <> "" Then
FromPath = "W:testing\" & x.Value '<< Change
ToPath = "W:testing\~Archive\" & Format(x.Offset(0, 1).Value - 30, "yyyy") & "\" & x.Value '<< Change
'Note: It is not possible to use a folder that exist in ToPath
'We created subfolders by year earlier so we can archive by year now
Set FSO = CreateObject("scripting.filesystemobject")
FSO.MoveFolder Source:=FromPath, Destination:=ToPath
End If
Next x
End Sub

Resources