VBA Skipping File Names that do not exist - excel

I am working on a code for my company that would take our production relief sheets and compile the data into one big document for compiling. I have a code that runs and does what I need it do; however, I have run into a problem. Our relief sheets are saved to our ShareDrive with the name of the current date (example: "4-27-2022"). Our site does not work on Saturdays or Sundays; therefore, we do not have relief sheets for Saturdays or Sundays. The code below works for importing data from a Monday-Friday, but it doesn't work if you want to look at dates that are separated by a weekend.
Is there a way to get excel to run my current code but skip the dates that do not have a file?
code:
Option Explicit
Sub ImportPolymerData()
'This sub imports the data from the polymer relief sheets based on the date range specified.
Dim StartDate As String, EndDate As String, SMonth As Integer, EMonth As Integer, d As String, dt As String
Dim StartY As String, SShortY As String, EndY As String, ShortEndY As String
Dim diff As Integer
Dim wbRS As Workbook 'Relief Sheet workbook
Dim wb As Workbook
Dim rng As Range
Dim r As Range
Dim dat As String
Dim i As Integer
Set wb = ThisWorkbook
Dim myPath As String
Dim myFile As String
Dim Dmonth As Integer
Application.ScreenUpdating = False
wb.Sheets("Inputs").Activate
StartDate = Range("B4").Value 'Pulls the start and end date out of cells B4 and B5
EndDate = Range("B5").Value
SMonth = Month(StartDate) 'Pulls the Month of the start and end date
EMonth = Month(EndDate)
StartY = Year(StartDate) 'Pulls the Year of the start and end date
EndY = Year(EndDate)
SShortY = Right(StartY, 2) 'Pulls the last two numbers of the year of the start and end date
ShortEndY = Right(EndY, 2)
'''Update FilePath after New Year'''
myPath = "\\cx.championx.com\AMER\US-Garyville\Groups\Champion X Operators\Polymer Relief Sheets\Polymer Relief Sheet Current\" & StartY
'Get date range difference
diff = DateDiff("d", StartDate, EndDate) 'Counts the number of days between the start and end date
'This will be the end of the loop for looping through the files
'MsgBox diff
'Clear Old Data
wb.Sheets("5B Polymer").Activate
wb.Sheets("5B Polymer").Range(Range("A2").End(xlToRight), Range("A2").End(xlDown)).Clear
On Error Resume Next 'tells excel to skip lines of code containing errors
'Loop through files
For i = 0 To diff 'From 0 to the # of days in the range of start date to end date
dat = wb.Sheets("Inputs").Range("B4").Value + i
Dmonth = Month(dat) 'Gets the month for whatever date you have going through the loop
'Format "dat" to find the Polymer Relief Sheet file
dt = Format(dat, "mm/dd/yyyy") 'Changes the date format to match the way dates are entered as relief sheet titles
d = Replace(dt, "/", "-")
'MsgBox d
'Opens the Relief sheet folder with the month of the dates
Select Case Dmonth
Case 1
myFile = myPath & "\01-JAN\" & d & ".xlsm"
Case 2
myFile = myPath & "\02-FEB\" & d & ".xlsm"
Case 3
myFile = myPath & "\03-MAR\" & d & ".xlsm"
Case 4
myFile = myPath & "\04-APR\" & d & ".xlsm"
Case 5
myFile = myPath & "\05-MAY\" & d & ".xlsm"
Case 6
myFile = myPath & "\06-JUN\" & d & ".xlsm"
Case 7
myFile = myPath & "\07-JUL\" & d & ".xlsm"
Case 8
myFile = myPath & "\08-AUG\" & d & ".xlsm"
Case 9
myFile = myPath & "\09-SEP\" & d & ".xlsm"
Case 10
myFile = myPath & "\10-OCT\" & d & ".xlsm"
Case 11
myFile = myPath & "\11-NOV\" & d & ".xlsm"
Case 12
myFile = myPath & "\12-DEC\" & d & ".xlsm"
End Select
'Open up
Set wbRS = Workbooks.Open(myFile)
'Unhides all hidden worksheets in the relief sheet workbook
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next ws
'Get polymer data
wbRS.Sheets("5B Batches").Activate
Application.CutCopyMode = False
'Range(range("A2").end (xltoright), range("A2").end(xldown)).select
Range(Range("A2").End(xlToRight), Range("A2").End(xlDown)).Copy
With wb.Sheets("5B Polymer")
If .Range("A2") = "" Then
.Range("A2").PasteSpecial Paste:=xlPasteValues
Else
.Range("A2").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If
Columns("A:A").Select
Selection.NumberFormat = "m/d/yyyy"
End With
Application.CutCopyMode = False
'save and close
wbRS.Close False
Next i
wb.Sheets("5B Polymer").Activate
Columns("A:A").Select
Selection.NumberFormat = "m/d/yyyy"
Range("A2").Select
Sheets("Inputs").Range("I2").Value = Now
End Sub
Any help is greatly appreciated!

Make sure you don't use Select and Activate
see How to avoid using Select in Excel VBA
Instead make sure you have all Range, Cells, Columns and Rows objects fully referenced to a workbook and worksheet
Never use On Error Resume Next to hide all error messages. Your code cannot work properly then (if it works it works only by accident but not on purpose). Use this line only to handle an expected error and always turn on error reporting right after that expected error as I did when opening the file. Here we expect that opening a file can error because a file does not exist. So we handle that by testing for Nothing to see if the file was opened.
Option Explicit
Public Sub ImportPolymerData()
'This sub imports the data from the polymer relief sheets based on the date range specified.
' Application.ScreenUpdating = False 'either turn it on in the end or leave it out. If you reference everything properly and don't use Select you don't need that.
Dim wb As Workbook
Set wb = ThisWorkbook
Dim StartDate As String
StartDate = wb.Sheets("Inputs").Range("B4").Value 'Pulls the start and end date out of cells B4 and B5
Dim EndDate As String
EndDate = wb.Sheets("Inputs").Range("B5").Value
Dim SMonth As Long
SMonth = Month(StartDate) 'Pulls the Month of the start and end date
Dim EMonth As Long
EMonth = Month(EndDate)
Dim StartY As String
StartY = Year(StartDate) 'Pulls the Year of the start and end date
Dim EndY As String
EndY = Year(EndDate)
Dim SShortY As String
SShortY = Right(StartY, 2) 'Pulls the last two numbers of the year of the start and end date
Dim ShortEndY As String
ShortEndY = Right(EndY, 2)
'''Update FilePath after New Year'''
Dim myPath As String
myPath = "\\cx.championx.com\AMER\US-Garyville\Groups\Champion X Operators\Polymer Relief Sheets\Polymer Relief Sheet Current\" & StartY
'Get date range difference
Dim diff As Long
diff = DateDiff("d", StartDate, EndDate) 'Counts the number of days between the start and end date
'This will be the end of the loop for looping through the files
'Clear Old Data
With wb.Sheets("5B Polymer")
.Range(.Range("A2").End(xlToRight), .Range("A2").End(xlDown)).Clear
End With
'don't do that without proper error handling!!!
'On Error Resume Next 'tells excel to skip lines of code containing errors
'Loop through files
Dim i As Long
For i = 0 To diff 'From 0 to the # of days in the range of start date to end date
Dim dat As String
dat = wb.Worksheets("Inputs").Range("B4").Value + i
Dim Dmonth As Long
Dmonth = Month(dat) 'Gets the month for whatever date you have going through the loop
'Format "dat" to find the Polymer Relief Sheet file
Dim dt As String
dt = Format$(dat, "mm/dd/yyyy") 'Changes the date format to match the way dates are entered as relief sheet titles
Dim d As String
d = Replace$(dt, "/", "-")
'Opens the Relief sheet folder with the month of the dates
Dim MonthFolders As Variant
MonthFolders = Array("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC")
'create file path and file name
Dim myFile As String
myFile = myPath & "\" & Format$(Dmonth, "00") & "-" & MonthFolders(Dmonth - 1) & "\" & d & ".xlsm"
'Try to open the file
Dim wbRS As Workbook 'Relief Sheet workbook
Set wbRS = Nothing
On Error Resume Next ' hide error just in next line!
Set wbRS = Workbooks.Open(myFile)
On Error GoTo 0 ' re-activate error reporting!!!
'run the following only if the file could be opened otherwise it does not exist
If Not wbRS Is Nothing Then
'Unhides all hidden worksheets in the relief sheet workbook
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next ws
'Get polymer data
Application.CutCopyMode = False
With wbRS.Worksheets("5B Batches")
.Range(.Range("A2").End(xlToRight), .Range("A2").End(xlDown)).Copy
End With
With wb.Worksheets("5B Polymer")
If .Range("A2") = vbNullString Then
.Range("A2").PasteSpecial Paste:=xlPasteValues
Else
.Range("A2").End(xlDown).Offset(1, 0).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If
wbRS.Worksheets("5B Batches").Columns("A:A").NumberFormat = "m/d/yyyy"
End With
Application.CutCopyMode = False
'!!! you don't save here!!! your comment is wrong or it needs to be SaveChanges:=True
'save and close
wbRS.Close SaveChanges:=False
End If
Next i
wb.Worksheets("5B Polymer").Columns("A:A").NumberFormat = "m/d/yyyy"
wb.Worksheets("Inputs").Range("I2").Value = Now
End Sub

Related

VBA activeworbook.close 1004 runtime error, missing folder path

Sub LoopThroughFolder()
Dim table As Range
Dim FSO
Dim month As String
Dim year As String
Dim FileName As String
Dim OldFileName As String
Dim MainPath As String
Dim ClientPath As String
Dim FullPath As String
Dim FileToOpen As Workbook
Dim Text As String
Application.ScreenUpdating = False
Set wb = ThisWorkbook
Set ws = wb.Worksheets("FileName")
month = ws.Range("E8")
year = ws.Range("F8")
OldFileName = ws.Range("R5")
MainPath = "C:\Document\documents\CPREIF_daily_test\"
ClientPath = MainPath & year & "\" & month & " - " & year & "\"
Set table = Range("B8", Range("B8").End(xlToRight).End(xlDown))
For Each Row In table.Rows
Text = Row.Cells(1, 1)
FileName = Row.Cells(1, 7)
Set FileToOpen = Workbooks.Open(ClientPath & OldFileName, UpdateLinks:=0)
Range("B4").ClearContents
Range("B4") = Text
Range("B4").NumberFormat = "dddd mmmm d" & ", " & "yyyy"
ActiveWorkbook.Close True, ClientPath & FileName
Next Row
MsgBox "Client Files Turned"
End Sub
Hey All. I wrote VBA to loop through each row of a table, renaming the workbook and changing the date within a cell, based off each row in a table. When I run the code within VBA editor, the code works. When I create a button and assign the macro to the button, I receive a runtime error. The code that breaks is:
ActiveWorkbook.Close True, ClientPath & FileName
Thanks!

Filter data is not getting copied to the new worksheet. Only blank file is getting saved

Goal of this code:
Apply filter at Range A2 in Final Salary Sheet based upon value of Menu Sheet Range "E6"
Copy A1:M1 data as header
and then Copy filter data to A2 range in new sheet, rename the new sheet and save the new sheet to specific folder with specified name.
Error I am facing:
A1:m1 range is perfectly getting copy pasted. but filter data is not getting copy pasted. Also please note A1 range in Final Salary Sheet is a Logo/Image.
Sub selfcopy()
Dim exclfile As String
Dim fdObj As Object
Dim year As String
Dim month As String
year = Sheets("Menu").Range("e4").Text
month = Sheets("Menu").Range("e6").Text
Application.ScreenUpdating = False
Set fdObj = CreateObject("Scripting.FileSystemObject")
If fdObj.FolderExists("\\Account\e\SATYA\BANK\1-SALARY SHEET\1-TRANSFER\" & year & "\" & month) Then
On Error Resume Next
Else
fdObj.CreateFolder ("\\Account\e\SATYA\BANK\1-SALARY SHEET\1-TRANSFER\" & year & "\" & month)
End If
Application.ScreenUpdating = True
exclfile = "Salary File" & "-" & Sheets("Menu").Range("E6").Text
Set Newbook = Workbooks.Add
ThisWorkbook.Worksheets("Final Salary").Select
Range("A1:M1").copy
Newbook.Worksheets("UBI Bank").Range("A1").Activate
Activesheet.paste
Newbook.Worksheets("Sheet1").Name = "Salaryoutput"
Newbook.Worksheets("Salaryoutput").Select
ThisWorkbook.Worksheets("Final Salary").Select
Range("A2").Select
ActiveSheet.Range("$A$2:$W$99999").AutoFilter Field:=1, Criteria1:=Array(1, Sheets("Menu").Range("E6").Text)
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Newbook.Worksheets("salaryoutput").Range("A2").Activate
ActiveSheet.Paste
Application.CutCopyMode = False
Newbook.SaveAs Filename:="\\Account\e\SATYA\BANK\1-SALARY SHEET\1-TRANSFER\" & year & "\" & month & "\" & exclfile
ThisWorkbook.Worksheets("Menu").Select
MsgBox ("Excel has been saved to Bank Folder")
End Sub
I am quite new with Excel VBA.
This line Newbook.Worksheets("UBI Bank").Range("A1").Activate fails because a new book will not have a sheet with that name.
Option Explicit
Sub selfcopy()
Const FOLDER = "\\Account\e\SATYA\BANK\1-SALARY SHEET\1-TRANSFER\"
Dim wbNew As Workbook
Dim fdObj As Object, exclfile As String, exclfolder As String
Dim year As Long, month As Long, lastrow As Long
With Sheets("Menu")
year = .Range("E4").Value2
month = .Range("E6").Value2
exclfile = "Salary File" & "-" & Format(month, "00")
exclfolder = FOLDER & year & "\" & month
End With
Set fdObj = CreateObject("Scripting.FileSystemObject")
If Not fdObj.FolderExists(exclfolder) Then
fdObj.CreateFolder exclfolder
MsgBox exclfolder & " created"
End If
Set wbNew = Workbooks.Add(1)
With wbNew
.Sheets(1).Name = "Salaryoutput"
End With
With Sheets("Final Salary")
lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
.Range("A1:M1").Copy wbNew.Sheets(1).Range("A1")
With .Range("A2:W" & lastrow)
.AutoFilter Field:=1, Criteria1:=month
.SpecialCells(xlCellTypeVisible).Copy wbNew.Sheets(1).Range("A2")
End With
End With
wbNew.SaveAs Filename:=exclfolder & "\" & exclfile
wbNew.Close savechanges:=False
Sheets("Menu").Activate
MsgBox "Excel has been saved to " & exclfile, vbInformation, exclfolder
End Sub

Copy data from a workbook to an existing workbook

I'm working on Excel for Mac, v16.53, with OS Catalina v10.15.7
I have an Excel workbook called SCRIPT with two sheets.
Sheet 1 has data entry areas and sheet 2 compiles those entries into a pseudo-table. The data in sheet 1 changes with every new person that is interviewed.
The data in sheet 2 is in columns A, B, H, I and J. It is non-contiguous and doesn't always have row 1 populated.
I can copy those five columns to a new csv file called Telesales-Leads-TODAY'S DATE.
The issue is when there already is a Telesales-Leads-TODAY'S DATE file.
The script is supposed to:
If Telesales-Leads-TODAY'S DATE file does not exist:
Start a new one.
Copy/paste the new SCRIPT data and save the Telesales-Leads-TODAY'S DATE file.
If a Telesales-Leads-TODAY'S DATE file does exist:
Copy the new data from the SCRIPT workbook to the first 100% empty column of the Telesales-Leads-TODAY'S DATE file.
Save the file with the same name (Telesales-Leads-TODAY'S DATE) in csv format.
It throws an error AFTER it copies the data from the SCRIPT workbook but BEFORE it has a chance to completely open the Telesales-Leads-TODAY'S DATE file.
I am using the MsgBox to debug.
Sub BackUpScriptData()
Dim strFileName As String
Dim strFileExists As String
Dim finalcolumn As Integer
Dim firstemptycolumn As Integer
Dim csvOpened As Workbook
Dim oneCell As Range
Dim myCSVFileName As String
Dim myWB As Workbook
Dim tempWB As Workbook
Dim rngToSave As Range
Dim col As String
Dim ColumnNumber As Integer
Dim ColumnLetter As String
Dim colstart As String
Dim CellAddress As String
Dim TestChar As String
Dim NumberToLetter As String
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
On Error GoTo err
strFileName = "/Users/XXXXXXXX/Library/Group Containers/XXXXXXXX.Office/User Content.localized/Startup.localized/Excel/" & "Telesales-Leads-" & VBA.Format(VBA.Now, "mm-dd-yyyy") & ".csv"
strFileExists = Dir(strFileName)
If strFileExists = "" Then
MsgBox strFileName & " ~~~~~~~~doesn't exist"
Set myWB = ThisWorkbook
myCSVFileName = "/Users/XXXXXXXX/Library/Group Containers/XXXXXXXX.Office/User Content.localized/Startup.localized/Excel/" & "Telesales-Leads-" & VBA.Format(VBA.Now, "mm-dd-yyyy") & ".csv"
Set rngToSave = Range("A1:B69,H1:J69")
rngToSave.Copy
Set tempWB = Application.Workbooks.Add(1)
With tempWB
.Sheets(1).Range("A1").PasteSpecial xlPasteValues
.SaveAs FileName:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
Else
Set myWB = ThisWorkbook
Set rngToSave = Range("A1:B69,H1:J69")
rngToSave.Copy
Set csvOpened = Workbooks.Open(FileName:=strFileName)
MsgBox "csvOpened is " & csvOpened
With csvOpened
Set oneCell = Range("A1")
Do While WorksheetFunction.CountA(oneCell.EntireColumn)
Set oneCell = oneCell.Offset(0, 1)
Loop
MsgBox "oneCell.Column is " & oneCell.Column
End With
CellAddress = Cells(1, ColNum).Address
For i = 2 To Len(CellAddress)
TestChar = Mid(CellAddress, i, 1)
If TestChar = "$" Then Exit For
NumberToLetter = NumberToLetter & Mid(CellAddress, i, 1)
Next i
MsgBox "colstart is " & colstart
With csvOpened
.Sheets(1).Range(colstart & "1").PasteSpecial xlPasteValues
.SaveAs FileName:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
End If
err: MsgBox "failed to copy."
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
The code is essentially the same for creating a new workbook or updating an existing, the only difference being the column where the data is to be pasted. As this is a csv file then UsedRange is a simple way to determine the last clear column.
Sub BackUpScriptData2()
Const FOLDER = "/Users/XXXXXXXX/Library/Group Containers/XXXXXXXX.Office/" & _
"User Content.localized/Startup.localized/Excel/"
Const PREFIX = "Telesales-Leads-"
Dim wb As Workbook, wbCSV As Workbook
Dim ws As Worksheet, rngToSave As Range
Dim colNum As Long, myCSVFileName As String
myCSVFileName = PREFIX & VBA.Format(VBA.Now, "mm-dd-yyyy") & ".csv"
' check if file exists
If Len(Dir(FOLDER & myCSVFileName)) = 0 Then
' not exists
MsgBox "'" & myCSVFileName & "'" & vbCrLf & _
"does not exist, it will be created", vbInformation, FOLDER
Set wbCSV = Workbooks.Add()
colNum = 1
Else
' exists
Set wbCSV = Workbooks.Open(FOLDER & myCSVFileName)
With wbCSV.Sheets(1).UsedRange
colNum = .Column + .Columns.Count
End With
MsgBox "'" & myCSVFileName & "'" & vbCrLf & _
"exists, it will extended from column " & colNum, vbInformation, FOLDER
End If
' copy and save
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet2")
Set rngToSave = ws.Range("A1:B69,H1:J69")
rngToSave.Copy
With wbCSV
.Sheets(1).Cells(1, colNum).PasteSpecial xlPasteValues
.SaveAs Filename:=FOLDER & myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
MsgBox "File saved to " & myCSVFileName, vbInformation, FOLDER
End Sub

EXCEL- Editing Excel's before copying to a new sheet with VBA

I have between 800 excels files that I need to transfer over to one sheet but before the transfer, I need to add a column ("A:A") and copy one cell value (before column added ("C1") after column ("D1")) and use column ("C:C") to get the range it would need to be pasted in column("A:A")
I have done the code already but struggling to add this on. If anyone can help that would be amazing.
Sub LoopThrough()
Dim MyFile As String, Str As String, MyDir As String
Dim sh As Worksheet, MasterRange As Range, TempWB As Workbook, TempSH As Worksheet, TempRng As Range, TempRow As Range
Dim NewMasterLine As Long
Dim StartTime As Double
Dim MinutesElapsed As String
StartTime = Timer
On Error GoTo ErrorHandler
Set sh = ThisWorkbook.Worksheets("Sheet1")
' Change address to suite
MyDir = "C:\"
MyFile = Dir(MyDir & "*.xls")
ChDir MyDir
' The following lines will put excel in a state similar to "frozen" mode. This will increase the code performance, as CPU will solely focus on performing
' the operations required by the code and not on showing the changes happening on excel
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim x As Long
x = 0
' Here starts the loop related to the files in folder
Do While MyFile <> ""
'TempWB is a Worksheet object - will be the importing worksheet. TempRng is the used range in sheet 1 of the workbook
Set TempWB = Workbooks.Open(FileName:=MyFile, UpdateLinks:=False, Password:=CalcPassword(MyFile))
Columns(1).Insert
Range("c2").Copy Range("A4:A10000")
Set TempSH = TempWB.Worksheets(1)
Set TempRng = TempSH.Range("A1:DB" & TempSH.Range("A" & TempSH.Rows.Count).End(xlUp).Row)
TempRng.Range("A:A").Insert ' This is where I tried to add in the extra column
TempRng.Range("A1").Value = TempRng.Range("D1").Value ' Tried doing this as a test but still pasted as if no changes had been made????
'NewMasterLine is the last used row (+1) of the Master Workbook (It is basically where the new rows will start to be imported)
NewMasterLine = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
If NewMasterLine > 1 Then NewMasterLine = NewMasterLine + 1
'This will loop through all the rows of the range to be imported, checking the first column.
' If the value in the second column is work-xne-ams, will import the single row in the master workbook
For Each TempRow In TempRng.Rows
If Left(TempRow.Cells(1, 2).Value, 5) = "SHIFT" Or TempRow.Row < 4 Then
'If TempRow.Cells(1, 2).Value = "SHIFT--1" Or TempRow.Row < 4 Then
Set MasterRange = sh.Range("A" & NewMasterLine & ":DA" & NewMasterLine)
MasterRange.Value = TempRow.Value
NewMasterLine = NewMasterLine + 1
End If
Next
TempWB.Close savechanges:=False
MyFile = Dir()
x = x + 1
ThisWorkbook.Worksheets("PWD").Range("H2") = x
Loop
ErrorHandler:
If Err.Number <> 0 Then MsgBox "An error occurred." & vbNewLine & vbNewLine & "Last file that was attempted to be opened: " & MyFile & vbNewLine & vbNewLine & Err.Description
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation
End Sub
Function CalcPassword(FileName As String) As String
CalcPassword = ""
On Error Resume Next
Dim TheFile As String: TheFile = Split(Split(FileName, "\")(UBound(Split(FileName, "\"))), ".")(0)
Dim PWD As Range: Set PWD = ThisWorkbook.Worksheets("PWD").ListObjects("PWD").DataBodyRange
CalcPassword = WorksheetFunction.VLookup(TheFile, PWD, 5, False)
End Function

Opening an excel file with the most recent date name in the file

I run a report on a daily basis called "Contract Values UK - dd-mm-yy"
where dd-mm-yy represents the day month and year the report was run.
I've tried the below code but this seems unable to locate the file.
Can someone help me adapt the below code - many thanks.
Sub OpenLatest()
a matching date
Dim dtTestDate As Date
Dim sStartWB As String
Const sPath As String = "C:\Users\Documents\Weekly Contract Values Analysis\"
Const dtEarliest = #1/1/2018#
dtTestDate = Date
sStartWB = ActiveWorkbook.Name
While ActiveWorkbook.Name = sStartWB And dtTestDate >= dtEarliest
On Error Resume Next
Workbooks.Open sPath & "Contract Values UK - " & Format(dtTestDate, "(DD-MM-YY)") & ".xlsm"
dtTestDate = dtTestDate - 1
On Error GoTo 0
Wend
If ActiveWorkbook.Name = sStartWB Then MsgBox "Earlier file not found."
End Sub
Is this what you are trying? (Untested)
I am assuming the file name is like Contract Values UK - dd-mm-yy.xlsm
Const sPath As String = "C:\Users\Documents\Weekly Contract Values Analysis\"
Const dtEarliest = #1/1/2018#
Sub Sample()
Dim i As Long
Dim dt As Date: dt = Date
Dim flName As String, dtPart As String
'~~> Loop through dates in reverse
For i = dt To dtEarliest Step -1
dtPart = Format(i, "dd-mm-yy")
'~~> Create your file name
flName = "Contract Values UK - " & dtPart & ".xlsm"
'~~> Check if exists
If Dir(sPath & flName) <> "" Then
MsgBox sPath & flName '<~~ You can now work with this file
Exit For
End If
Next i
End Sub

Resources