Creating Multiple PDF Files from Form - excel

i need some help with the code below, i got this code on a tutorial and it`s working fine for me, the point of this question is, the code below only generate 1 PDF from a constant PDF Form, using Cells "A2" and "B2". How can i make a Loop, so the code generate 1 PDF file based on each row from sheet with text?
Im providing the code below. I would be very grateful for the help and time.
Option Explicit
Sub Write_to_pdf_form()
'declaring variables
Dim pdfApp As Acrobat.AcroApp
Dim pdfDoc As Acrobat.AcroAVDoc
Dim Support_doc As Acrobat.AcroPDDoc
Dim pdffile
Dim wsDocs As Worksheet
Dim outputname
'declaring output path
pdffile = "C:\Users\User\Documents\testesbulkpdf\Forms.pdf"
Dim pdf_form As AFORMAUTLib.AFormApp
'declaring fields
Dim num_doc As AFORMAUTLib.Field
Dim desc_doc As AFORMAUTLib.Field
Set pdfApp = CreateObject("AcroExch.App")
Set pdfDoc = CreateObject("AcroExch.AVDoc")
If pdfDoc.Open(pdffile, "") = True Then
pdfDoc.BringToFront
pdfApp.Show
'setting fields names
Set pdf_form = CreateObject("AFORMAUT.App")
Set num_doc = pdf_form.Fields("N")
Set desc_doc = pdf_form.Fields("descrição documento")
'setting fields values
num_doc.Value = Worksheets("docs").Range("A2").Value
desc_doc.Value = Worksheets("docs").Range("B2").Value
'setting output name of PDF
outputname = "Doc." & num_doc.Value & "-" & desc_doc.Value
Set Support_doc = pdfDoc.GetPDDoc
If Support_doc.Save(PDSaveFull, "C:\Users\User\Documents\testesbulkpdf\" & outputname & ".pdf") Then
Debug.Print "Saved"
Else
Debug.Print "Failed to save the doc"
End If
pdfDoc.Close True
Support_doc.Close
pdfApp.Exit
Set num_doc = Nothing
Set desc_doc = Nothing
Set pdfDoc = Nothing
Set Support_doc = Nothing
Set pdfApp = Nothing
End If
End Sub

I got it, using For Each, and some labels, i got it working just great.
For Each cell In Worksheets("docs").Range("A2:B500")
If cell.Value = "" Then
GoTo Line4
End If
If cell.Column = 1 Then
cell.Activate
If ActiveCell.Value <> "" Then
num_doc.Value = ActiveCell.Value
GoTo Line1
End If
End If
If cell.Column = 2 Then
cell.Activate
If ActiveCell.Value = "" Then
GoTo Line1
Else: desc_doc.Value = ActiveCell.Value
If desc_doc.Value <> "" And num_doc.Value <> "" Then
GoTo Line3
End If
End If
End If
If desc_doc Or num_doc = "" Then
GoTo Line4
End If
Line3:
outputname = "Doc." & num_doc.Value & "-" & desc_doc.Value
Set Support_doc = pdfDoc.GetPDDoc
If Support_doc.Save(PDSaveFull, "C:\Users\User\Documents\testesbulkpdf\" & outputname
& ".pdf") Then
Debug.Print "Saved"
Else
Debug.Print "Failed to save the doc"
End If
Line1:
Next cell
Line4:
pdfDoc.Close True
Support_doc.Close
pdfApp.Exit
Set num_doc = Nothing
Set desc_doc = Nothing
Set pdfDoc = Nothing
Set Support_doc = Nothing
Set pdfApp = Nothing
End Sub

Related

Loop through a PowerPoint presentation and replace certain keywords with text

I was hoping to get some help. I have the following code that works on replacing text from a word documents with a certain word in excel. For example I have ClientName in a cell and the Cell next to it has John, so each time the word ClientName is found it is replaced with John and so on. Here is the code that works for word documents. Can it be altered to work for .pptx too?
Sub AutoContract()
Dim cell As Range
Dim rng As Range
Dim wdApp As New Word.Application
Dim wdDoc As Word.Document
Dim wdDoc2 As Word.Document
Dim FilePath As String
Dim FilePath2 As String
Dim ending As String
Dim rngPara As Range
Dim Prompt As String
Dim Filesave As String
Dim FileSave2 As String
On Error GoTo ErrorHandler
Set wdApp = Nothing
FilePath = ThisWorkbook.Path
FilePath2 = Left(FilePath, InStr(FilePath, "\Calculations") - 1)
Filename = "Filename.docx"
StrDoc = FilePath2 & "\Inputs" & "\" & Filename
Set wdDoc2 = wdApp.Documents.Open(StrDoc)
Set rngPara = Range("A1:Z1058").Find("Variable Parameters")
If rngPara Is Nothing Then
MsgBox "Variable Parameters column was not found."
GoTo ErrorHandler
End If
Set rng = Range(rngPara, rngPara.End(xlDown))
wdApp.Visible = True
For Each cell In rng
If cell.Value = "" Then Exit For
With wdDoc2.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWildcards = False
.Wrap = wdFindContinue
.Text = cell.Value
.Replacement.Text = cell.Offset(0, 1)
.Execute Replace:=wdReplaceAll
End With
Next
SaveAsName = Left(FilePath, InStr(FilePath, "\Calculations") - 1) & "\Outputs\" & Range("EmployName").Value & " " & Range("TodayDate").Value & " Contract" & ".docx"
wdDoc2.SaveAs2 SaveAsName
ErrorExit:
Set wdApp = Nothing
Exit Sub
ErrorHandler:
If Err.Number = 5174 Then
MsgBox "Please check the file name you specified is correct."
Resume ErrorExit
Else
MsgBox "Error No: " & Err.Number & "; There is a problem"
If Not wdApp Is Nothing Then
wdApp.Quit False
End If
Resume ErrorExit
End If
End Sub

export from Excel to Word takes very long time on MAC

I have a script that exports specific range of cell from Excel to Word. Below you can see the script
Sub Export_to_Word_Mac()
Dim filename As String
Dim FolderName As String
Dim Folderstring As String
Dim FilePathName As String
Dim sh As Worksheet
Dim print_area As Range
Dim appWD As Object
Dim wddoc As Object
Dim rng As Range
Dim paragraphCount As Long
Set sh = ThisWorkbook.Sheets("Sheet1")
sh.Unprotect
sh.Rows("15:16").EntireRow.Hidden = True
For Each rng In sh.Range("B17:B26")
If rng.Value Like "wpisz zakres usług tutaj..." Then
rng.EntireRow.Hidden = True
Else
rng.EntireRow.Hidden = False
End If
Next rng
sh.Protect
FolderName = "Export"
filename = sh.Range("G4") & "_test_" & Format(Now, "dd-mm-yyyy_hhmm") & ".docx"
Folderstring = CreateFolderinMacOffice2016(NameFolder:=FolderName)
FilePathName = Folderstring & Application.PathSeparator & filename
On Error Resume Next
Set appWD = GetObject(, "Word.application")
If Err = 429 Then
Set appWD = CreateObject("Word.application")
Err.Clear
End If
Set wddoc = appWD.Documents.Add
appWD.Visible = True
With appWD.ActiveDocument.PageSetup
.TopMargin = appWD.InchesToPoints(0.5)
.BottomMargin = appWD.InchesToPoints(0.5)
.LeftMargin = appWD.InchesToPoints(0.5)
.RightMargin = appWD.InchesToPoints(0.5)
End With
'copy range to word
Set print_area = sh.Range("B1:C27")
print_area.Copy
'paste range to Word table
paragraphCount = wddoc.Content.Paragraphs.Count
wddoc.Paragraphs(paragraphCount).Range.Paste
Application.CutCopyMode = False
appWD.ActiveDocument.Tables(1).Rows.Alignment = wdAlignRowCenter
appWD.ActiveDocument.Cells.VerticalAlignment = wdCellAlignVerticalTop
'appWD.Activate
appWD.ActiveDocument.SaveAs (FilePathName)
MsgBox "Plik zostal zapisany jako: " & vbNewLine & filename & vbNewLine & _
" w nowo stworzonym " & FolderName & " w folderze: " & vbNewLine & "Library/Group Containers/UBF8T346G9.Office/"
appWD.Quit
Set wddoc = Nothing
Set appWD = Nothing
End Sub
Function CreateFolderinMacOffice2016(NameFolder As String) As String
Dim OfficeFolder As String
Dim PathToFolder As String
Dim TestStr As String
OfficeFolder = MacScript("return POSIX path of (path to desktop folder) as string")
OfficeFolder = Replace(OfficeFolder, "/Desktop", "") & _
"Library/Group Containers/UBF8T346G9.Office/"
PathToFolder = OfficeFolder & NameFolder
On Error Resume Next
TestStr = Dir(PathToFolder & "*", vbDirectory)
On Error GoTo 0
If TestStr = vbNullString Then
MkDir PathToFolder
'MsgBox "You find the new folder in this location :" & PathToFolder
End If
CreateFolderinMacOffice2016 = PathToFolder
End Function
Unfortunetely, there are a couple of issues:
It takes 1,5-2 minutes to export and save the Word file. Could you please help me to optimize the code?
I need to open Word application on my Mac to run the script. Otherwise I get Run-time error '9' (Script out of Range). The issue is with this line: Set appWD = GetObject(, "Word.application") .
The only solution I came up with is to use .CopyPicture xlScreen and paste it to Word document. I takes arpund 5 second create Word file, however the content is not editable and it is saved as image.
Option 1: Keep using Copy but optimize VBA execution
There are many options to improve speed execution in Excel VBA (see this articles for more details), but the most useful when copy-pasting is certainly to set :
Application.ScreenUpdating = False
However, since you are pasting in Word, you'd have to do the same this for the Word Application to get the maximum speed improvement:
appWD.ScreenUpdating = False
Note: Make sure to reset Application.ScreenUpdating = True at the end of your code.
Option 2 : Use an array to transfer the data
If the formatting of the cell in Excel is not necessary, then you could load the content of the cells into an array and write this array to the word document like this:
'copy range to word
Dim DataArray() As Variant
DataArray = sh.Range("B1:C27").Value
Dim i As Integer, j As Integer
Dim MyWordRange As Object
Set MyRange = appWD.ActiveDocument.Range(0, 0)
appWD.ActiveDocument.Tables.Add Range:=MyRange, NumRows:=UBound(DataArray, 1), NumColumns:=UBound(DataArray, 2)
'paste range to Word table
For i = 1 To UBound(DataArray, 1)
For j = 1 To UBound(DataArray, 2)
appWD.ActiveDocument.Tables(1).Cell(i, j).Range.Text = DataArray(i, j)
Next j
Next i
Note that option 1 and 2 are not necessarily mutually exclusives.

Screen alerts in Acrobat stopping VBA code

I have this VBA code that searches through PDF files on my computer. Here is the code:
Option Explicit
Sub FindTextInPDF()
Dim TextToFind As String
Dim PDFPath As String
Dim App As Object
Dim AVDoc As Object
Dim DS As Worksheet
Dim SS As Worksheet
Set DS = Sheets("Report")
Set SS = Sheets("Search Index")
Dim sslastrow As Long
Dim dslastrow As Long
Dim b As Integer
Dim J As Integer
With SS
sslastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
With DS
dslastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
For b = 2 To dslastrow
PDFPath = "C:\Users\desposito\Documents\Temp\" &
Sheets("Report").Range("E" & b).Value & Sheets("Report").Range("B" &
b).Value & ".pdf"
If Dir(PDFPath) = "" Then
GoTo nextb
End If
If LCase(Right(PDFPath, 3)) <> "pdf" Then
GoTo nextb
End If
On Error Resume Next
Set App = CreateObject("AcroExch.App")
If Err.Number <> 0 Then
Set App = Nothing
GoTo nextb
End If
Set AVDoc = CreateObject("AcroExch.AVDoc")
If Err.Number <> 0 Then
Set AVDoc = Nothing
Set App = Nothing
GoTo nextb
End If
On Error GoTo 0
If AVDoc.Open(PDFPath, "") = True Then
AVDoc.BringToFront
Else
App.Exit
Set AVDoc = Nothing
Set App = Nothing
GoTo nextb
End If
For J = 2 To sslastrow
TextToFind = SS.Range("B" & J).Value
If AVDoc.FindText(TextToFind, False, False, True) = False Then
GoTo NextJ
Else:
DS.Range("Q" & b).Value = DS.Range("Q" & b).Value & TextToFind & ";"
& " "
End If
NextJ:
Next
AVDoc.Close True
App.Exit
Set AVDoc = Nothing
Set App = Nothing
nextb:
Next
End Sub
However, every 100ish files, I will get this notification:
"Reader has finished searching the document. No matches were found."
All I have to do is hit enter and then the code runs for another 10-30 minutes before I get the notification again. It seems to be randomly happening in the middle of searching through the document which is this part of the code:
For J = 2 To sslastrow
TextToFind = SS.Range("B" & J).Value
If AVDoc.FindText(TextToFind, False, False, True) = False Then
GoTo NextJ
Else:
DS.Range("Q" & b).Value = DS.Range("Q" & b).Value & TextToFind & ";"
& " "
End If
NextJ:
I looked into disabling screen alerts in acrobat, but it doesn't look like I can do that.

delete blue and empty cells from xlsx with vbscript

I've got a vbscript that converts a specific range of rows to a csv file.
My problem is it also copies empty rows and not needed blue rows. How can I delete this complete empty rows before copying or exclude them from copying?
My code:
Public Sub xlsToCsv()
Const WorkingDir = "C:\Test\"
Const xlCSV = 24
Const xlUp = -4162
Dim fso, SaveName, myFile
Dim objExcel, objWorkbook, wsSource, wsTarget
myFile = "source_file.xlsx"
SaveName = "test.csv"
With CreateObject("Scripting.FilesystemObject")
If Not .FileExists(WorkingDir & myFile) Then
MsgBox "File not found:" & vbCrLf & WorkingDir & myFile, vbInformation, "Script Cancelled"
WScript.Quit
End If
End With
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False
Set objWorkbook = objExcel.Workbooks.Open(WorkingDir & myFile)
Set wsSource = objWorkbook.Sheets(1)
Set wsTarget = objWorkbook.Sheets.Add()
With wsTarget
.Cells(1,1).Value = "ID"
.Cells(1,2).Value = "NAME"
.Cells(1,3).Value = "DESC"
End With
With wsSource
.Range("F7", .Range("F" & .Rows.Count).End(xlUp)).Copy wsTarget.Range("A2")
.Range("A7", .Range("A" & .Rows.Count).End(xlUp)).Copy wsTarget.Range("B2")
.Range("E7", .Range("E" & .Rows.Count).End(xlUp)).Copy wsTarget.Range("C2")
End With
objWorkbook.SaveAs WorkingDir & SaveName, xlCSV
objWorkbook.Close True
Set objWorkbook = Nothing
Set objExcel = Nothing
Set fso = Nothing
Set myFolder = Nothing
End Sub
call xlsToCsv()
Option explicit
'// Define the blue color here
dim ibluecolor: ibluecolor = 15652797 ' this is 40% Accent1
Public Sub xlsToCsv()
Const WorkingDir = "C:\Test\"
Const xlCSV = 24
Const xlUp = -4162
Dim fso, SaveName, myFile, myFolder
Dim objExcel, objWorkbook, wsSource, wsTarget
myFile = "source_file.xlsx"
SaveName = "test.csv"
With CreateObject("Scripting.FilesystemObject")
If Not .FileExists(WorkingDir & myFile) Then
MsgBox "File not found:" & vbCrLf & WorkingDir & myFile, vbInformation, "Script Cancelled"
WScript.Quit
End If
End With
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False
Set objWorkbook = objExcel.Workbooks.Open(WorkingDir & myFile)
Set wsSource = objWorkbook.Sheets(1)
Set wsTarget = objWorkbook.Sheets.Add()
With wsTarget
.Cells(1,1).Value = "ID"
.Cells(1,2).Value = "NAME"
.Cells(1,3).Value = "DESC"
End With
dim Fcol, Acol, Ecol
With wsSource
set Fcol = .Range("F7", .Range("F" & .Rows.Count).End(xlUp))
set Acol = .Range("A7", .Range("A" & .Rows.Count).End(xlUp))
set Ecol = .Range("E7", .Range("E" & .Rows.Count).End(xlUp))
End With
With wsTarget
Fcol.Copy .Range("A2")
Acol.Copy .Range("B2")
Ecol.Copy .Range("C2")
End With
dim Frc, Arc, Erc
Frc = Fcol.Rows.Count
Arc = Acol.Rows.Count
Erc = Ecol.Rows.Count
dim rowcount
rowcount = Max(Arc, Frc, Erc)
dim ix
with wsTarget
for ix = rowcount + 1 to 2 step -1
if Len(.cells(ix,1))=0 and len(.cells(ix,2))=0 and len(.cells(ix,3))=0 then
.rows(ix).delete
'//Check for blue rows assuming all cells in the row have the same color
elseif .cells(ix, 1).Interior.Color = iBlueColor then
.rows(ix).delete
end if
next
End With
objWorkbook.SaveAs WorkingDir & SaveName, xlCSV
objWorkbook.Close True
Set objWorkbook = Nothing
Set objExcel = Nothing
Set fso = Nothing
Set myFolder = Nothing
End Sub
call xlsToCsv()
Function Max(v1, v2, v3)
select case true
case v1 => v2 and v1 => v3
Max = v1
case v2 => v3
Max = v2
case else
Max = v3
end select
end function
This is an alternative approach to my original in an attempt to improve performance. In this case, instead of using Excel to create the csv file, the VBScript code writes the csv file directly using a text file created by FileSystemObject. I have tested this with a larger set of source data and it seems to be quite a bit quicker than the original - about 40 seconds for 1500 rows. There is still an overhead of opening the Excel application (about 5-10 seconds) but there's not much you can do about that. If performance is important to you there may be other improvements that you could do.
If you have numeric values in the spreadsheet, you may need to do some formatting to convert to string values suitable for csv output, because Excel tends to use exponential notation for numbers converted to text, which is not always what you want. I have also used quotation marks and comma separators but you could use different formatting conventions for your CSV output. You may want to change the use of WriteLine because this appends a CrLf after the last line, which might be interpreted downstream as a blank row.
Option explicit
'// Define the blue color here
dim ibluecolor: ibluecolor = 15652797 ' this is 40% Accent1
msgbox "starting"
call xlsToCsv()
msgbox "finished"
Public Sub xlsToCsv()
Const WorkingDir = "C:\Test\"
Const xlCSV = 24
Const xlUp = -4162
Dim fso, SaveName, myFile, myFolder
Dim objExcel, objWorkbook, wsSource, wsTarget
Dim oOutputFile
myFile = "source_file.xlsx"
SaveName = "test2.csv"
With CreateObject("Scripting.FilesystemObject")
'// Check that the input file exists
If Not .FileExists(WorkingDir & myFile) Then
MsgBox "File not found:" & vbCrLf & WorkingDir & myFile, vbInformation, "Script Cancelled"
WScript.Quit
End If
'// Create a text file to be the output csv file
'// Overwrite v v False=ASCII format use True for Unicode format
set oOutputFile = .CreateTextFile( WorkingDir & SaveName, True, False)
End With
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False
Set objWorkbook = objExcel.Workbooks.Open(WorkingDir & myFile)
Set wsSource = objWorkbook.Sheets(1)
oOutputFile.WriteLine """ID"",""NAME"",""DESC"""
'// Get the three column ranges, starting at cells in row 7
dim Fcol, Acol, Ecol
With wsSource
set Fcol = .Range("F7", .Range("F" & .Rows.Count).End(xlUp))
set Acol = .Range("A7", .Range("A" & .Rows.Count).End(xlUp))
set Ecol = .Range("E7", .Range("E" & .Rows.Count).End(xlUp))
End With
'// Get the number of rows in each column
dim Frc, Arc, Erc
Frc = Fcol.Rows.Count
Arc = Acol.Rows.Count
Erc = Ecol.Rows.Count
'// Rowcount is the max row of the three
dim rowcount
rowcount = Max(Arc, Frc, Erc)
dim AVal, FVal, EVal
dim ix
for ix = 1 to rowcount
'// Note - row 1 of each column is actually row 7 in the workbook
AVal = REPLACE(ACol.Cells(ix, 1), """", """""")
EVal = REPLACE(ECol.Cells(ix, 1), """", """""")
FVal = REPLACE(FCol.Cells(ix, 1), """", """""")
'// Check for an empty row
if Len(AVal)=0 and len(EVal)=0 and len(FVal)=0 then
'// skip this row
'// Check for a blue row
elseif ACol.cells(ix,1).Interior.Color = iBlueColor then
'// skip this row
else
'// Write the line to the csv file
oOutputFile.WriteLine """" & FVal & """,""" & AVal & """,""" & EVal & """"
end if
next
'// Close the output file
oOutputFile.Close
'// Close the workbook
objWorkbook.Close True
objExcel.Quit
'// Clean up
Set oOutputFile = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
Set fso = Nothing
Set myFolder = Nothing
End Sub
Function Max(v1, v2, v3)
select case true
case v1 >= v2 and v1 >= v3
Max = v1
case v2 >= v3
Max = v2
case else
Max = v3
end select
end function

Organizing Files in Excel using VBA and FileSystemObject

I tried to get this to sort in ascending order from the time and it is not quite working right. It adds all the information, but does not sort the value. Also, I need to add a cut-off so it only uploads the files within the last week (7 days) from the current date. I'm not sure of an effective way to do this.
Thanks!
Option Explicit
Sub ListFiles()
Application.ScreenUpdating = False
Sheets("Sheet2").Select
With Range("A1")
.Formula = "Folder contents:"
.Font.Bold = True
.Font.Size = 12
End With
Range("A3").Formula = "Folder Path:"
Range("B3").Formula = "File Name:"
Range("C3").Formula = "Creation Date:"
ListFolders "C:\Users\blake.rupprecht\Desktop\Photos\"
Application.ScreenUpdating = True
End Sub
Sub ListFolders(SourceFolderName As String)
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.Folder
Dim r As Long
Dim sfil As String
Dim par As String
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
On Error Resume Next
sfil = Dir(SourceFolderName & "\" & "*.jpg*")
Do Until sfil = ""
Range("B" & Rows.Count).End(xlUp).Offset(1).Select
ActiveCell.Hyperlinks.Add ActiveCell, SourceFolderName & "\" & sfil, , , sfil
ActiveCell.Offset(, 1).Value = SourceFolder.Files(sfil).DateCreated
ActiveCell.Offset(1).Select
sfil = Dir$
Loop
Columns("A:B").AutoFit
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub
Checking for 7 days tmie span:
If Now - SourceFolder.Files(sfil).DateCreated < 7 Then
Range("B" & Rows.Count).End(xlUp).Offset(1).Select
ActiveCell.Hyperlinks.Add ActiveCell, SourceFolderName & "\" & sfil, , , sfil
ActiveCell.Offset(, 1).Value = SourceFolder.Files(sfil).DateCreated
ActiveCell.Offset(1).Select
End If
Please note that the calculation takes time of day into consideration also. If you want just the date, you have to extract integers from operands.
To sort the values, record some sorting and then remodule that code to fit your scenario.
If you want to sort in ascending order, the easiest thing would probably be to add the results to an array, then use a comparison to re-order the array in ascending order, and then write the values to the cells from the array. I'll post an example when I get back to the office.
Code is untested, but should work. Let me know if it doesn't and I'll setup a workbook to test it in. Also, you could break the sorting code out into it's own function, then it's reusable in other routines. Do as you see fit.
I removed the On Error Resume Next statement because it wasn't necessary where you had it. Turning off error notifications is only going to mask errors and make it harder to troubleshoot problems with your code. If you expect errors, write something to handle them, don't just ignore them.
Option Explicit
Sub ListFiles()
Application.ScreenUpdating = False
Sheets("Sheet2").Select
With Range("A1")
.Formula = "Folder contents:"
.Font.Bold = True
.Font.Size = 12
End With
Range("A3").Formula = "Folder Path:"
Range("B3").Formula = "File Name:"
Range("C3").Formula = "Creation Date:"
ListFolders "C:\Users\blake.rupprecht\Desktop\Photos\"
Application.ScreenUpdating = True
End Sub
Sub ListFolders(SourceFolderName As String)
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.Folder
Dim r As Long
Dim sfil As String
Dim par As String
Dim lngX As Long
Dim lngY As Long
Dim strX As String
Dim strY As String
Dim strTemp As String
Dim strFiles() As String
ReDim strFiles(0)
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
sfil = Dir(SourceFolderName & "\*.jpg*")
Do Until LenB(sfil) = 0
If Now - SourceFolder.files(sfil).DateCreated < 7 Then
If lngX = 0 And LenB(strFiles(lngX)) = 0 Then
strFiles(0) = sfil
Else
ReDim Preserve strFiles(UBound(strFiles) + 1)
strFiles(UBound(strFiles)) = sfil
End If
End If
Loop
'Sort the array in ascending order
If LenB(srfiles(LBound(strFiles))) > 0 Then
For lngY = 0 To UBound(strFiles) - 1
For lngX = 0 To UBound(strFiles) - 1
'Grab the current and next item in the list to compare
strX = strFiles(lngX)
strY = strFiles(lngX + 1)
'Check if the current item is greater than the next in the list and swap them if it is
If strX > strY Then
strTemp = strFiles(lngX)
strFiles(lngX) = strFiles(lngX + 1)
strFiles(lngX + 1) = strTemp
End If
'Reset the temporary strings so we don't accidentally use the wrong value in case of some unforeseen error
strTemp = vbNullString
strX = vbNullString
strY = vbNullString
Next lngX
Next lngY
End If
For lngX = LBound(strFiles) To UBound(stfiles)
With Range("B" & Rows.Count).End(xlUp).offset(1)
.Hyperlinks.Add ActiveCell, SourceFolderName & "\" & strFiles(lngX), , , strFiles(lngX)
.offset(, 1).Value = SourceFolder.files(strFiles(lngX)).DateCreated
End With
Next
Columns("A:B").AutoFit
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub

Resources