How can I pull open a file by most recent fiscal month? - excel

I have a line of code to open up a workbook based on a dt string that I specify.
Const filename = "Labor_Data_"
Const basepath = "C:\Users\CDL File"
Dim wbPreviousData as workbook
Dim dt As String: dt = Format(DateAdd("m", -1, Now), "mm_yyyy")
and then I open up the previous months file with:
Set wbPreviousData = Workbooks.Open(basepath & "\" & filename & dt & ".xlsx")
But I realize that my company's fiscal calendar can sometimes span 5 weeks, e.g. (last week of March - to - first week of May)
Is there an easy way to update my code to just reference the most recent month that is saved in a file pathway that I specify?

You have to scan all the files in the directory to find the latest
Sub findlatest()
Const filename = "Labor_Data_"
Const basepath = "C:\Users\CDL File"
Dim file As String, absfile As String
Dim latest As String, ts As Double, tsmax As Double
file = Dir(basepath & "\" & filename * "*")
Do While Len(file) > 0
' check timestamp
absfile = basepath & "\" & file
ts = CDbl(FileDateTime(absfile))
If ts > tsmax Then
tsmax = ts
latest = file
End If
file = Dir
Loop
Debug.Print latest
End Sub

Related

Determine current month to open file based on path and name that changes monthly

I am writing in Microsoft 2010 OS and Excel 365. I have written a script to process a 150K row file.
It opens a source file located in a SharePoint drive:
"\(server name)\SQL Files\2022\06.2022\June2022Name.xlsx"
There are files for each month over the past year and a new folder is created as the months progress.
In June, there is no folder for July but it will be written as
2022\07.2022\July2022Name.xlsx
I would like to open the file that matches the current month.
This is what I tried so far
'Find Workbook Filename <br>
Dim dt as String, dt2 as string
Filename as String, strMonth as string<br>
strMth = Monthname(Month(Now()), True<br>
if Month(Now()) = 1 Then<br>
strPriorMth = MonthName(12,True)<br>
Else st PriorMth = Monthname(Month(Now())-1, True<br>
dt2 = StrMonth(mm).YYYY
dt = StrMonth(mmm)YYYY
<br>
filename = "\\(server name)\SQL Files\2022\"dt2"\"dt & "SqlViews.xlsx"<br>
I'm unsure how to cast the dt2 as a number string and dt as what I think is a nvarchar string.
Not sure the exact output you want. But here is an example.
Sub test()
Dim dt As String, dt2 As String
Dim filename As String, strMonth As String
strMth = MonthName(Month(Now()))
If Month(Now()) = 1 Then
mth = "12"
strPriorMth = MonthName(12, True)
Else
mth = Month(Now() - 1)
strPriorMth = MonthName(Month(Now()) - 1, True)
End If
dt = Format(mth, "mm")
dt2 = Format(mth, "mmm")
filename = "\\(server name)\SQL Files\2022\" & dt2 & "\" & dt & "SqlViews.xlsx"
Debug.Print filename
End Sub

Collate several files, each housed in separate folders, into a single folder

I need to copy 20+ files, each housed by unique folders, into a single folder. I know this should be fairly simple. I've created the below code but I keep getting a Compile Error: Object required error box. The below code looks sound to me so I'm really struggling to find where the error is.
Folder name is the date of the report (eg. 090118), hence, I decided to use a loop until the end of the month (931). I also added an error handling code so we can skip the holidays and weekends.
Sub CopyFiles()
Dim NewFolder As String
Dim NDay As Long
Dim FileName As String
Dim Month As Variant
Month = InputBox("Enter month, eg. 01-January")
NewFolder = "C:\Results\Trading\2018\" & Month & "\Backtest Daily Files\Daily GS\" 'Don't forget to edit this
NDay = 901
On Error Resume Next
Do While NDay < 931
FileName = Dir("C:\Reports\2018\" & Month & "\0" & NDay & "18\GS_Futures*.cs*")
FileCopy FileName, NewFolder
NDay = NDay + 1
Loop
End Sub
Dir doesn't return the full path. It either returns the file name only if found or a zero-length string if not found. If you want a definitive path and file name reference then you need to prefix the returned string with the folder.
An example would be,
...
Do While NDay < 931
FileName = Dir("C:\Reports\2018\" & Month & "\0" & NDay & "18\GS_Futures*.cs*")
if cbool(len(filename)) then _
FileCopy "C:\Reports\2018\" & Month & "\0" & NDay & "18\" & FileName, NewFolder
NDay = NDay + 1
loop
...
Seems to me that it would be easier to perform a recursive folder search within C:\Reports\2018\ but that's just MO. Relying on a user to type static input like 01-January unerringly is folly.
Found a solution. Needs some tweaking, but I'm all set for now. Thank you to all who took the effort to help. The problem was that I wasn't giving a file name to the destination just the folder (no .csv).
Sub CopyFiles()
Dim NewFolder As String
Dim NDay As Long
Dim FileName As String
Dim Month As String
Month = InputBox("Enter month, eg. 01-January")
NDay = 901
On Error Resume Next
Do While NDay < 931
FileName = "M:\MRL\2018\" & Month & "\0" & NDay & "18\GS_Futures_0" & NDay & "18.csv"
NewFolder = "M:\RMC reports\Trading\2018\" & Month & "\Backtest Daily Files\Daily GS\GS_Futures_0" & NDay & "18.csv"
FileCopy FileName, NewFolder
NDay = NDay + 1
Loop
End Sub
...

How to modify the VBA code that finds Oldest File date in a folder to find Newest File date in a folder?

The below code helps in finding the oldest file date in a folder, but I am looking for a VBA code that can be help me in finding the newest file date or most recent file date in a folder.
Sub oldestdate()
Range("G10").Value = GetOldestFile("C:\Users\xxx\Downloads\My files")
End Sub
Public Function GetOldestFile(ByVal FileFolder As String, _
Optional ByVal FileMask As String = "*.*", _
Optional ByVal FullName As Boolean = True) As String
Dim FoundFile As String
Dim FileDT As Date
Dim NewestFile As String
Dim NewestDT As Date
Dim FS As Object
'// Get rid of any terminating '\' just to get to a known state
If Right(Trim(FileFolder), 1) = "\" Then
FileFolder = Left(FileFolder, Len(Trim(FileFolder)) - 1)
End If
'// Get First file found in described folder
FoundFile = Dir$(FileFolder & "\" & FileMask)
'// Default return date
NewestDT = DateValue("1900-01-01")
Set FS = CreateObject("Scripting.FileSystemObject")
'// Loop through the rest of the files in that folder
Do Until FoundFile = ""
FileDT = FS.GetFile(FileFolder & "\" & FoundFile).DateCreated
'// Compare Current File datetime with oldest found
If FileDT > NewestDT Then
NewestFile = FoundFile
NewestDT = FileDT
End If
'// Get next file
FoundFile = Dir$
Loop
Set FS = Nothing
GetOldestFile = Format(NewestDT, "mm/dd/yyyy")
End Function
Please let me know how to find the newest file date in a folder.
You just have to revert the // Compare Current File datetime with oldest found part to look for a newer date instead for an older one:
First initialise with a reasonably old date:
NewestDT = DateValue("1900-01-01")
And change the target condition:
...
If FileDT > NewestDT Then
NewestDT = FileDT
...
End if
You might have to adapt the initialization for the oldest date, I didn't test it. I also suggest you change the naming of the variables.

How to take end part of a string and concat to another string?

Updating a script for efficiency. A JAL Script calls the VBScript in a loop to check each file in a txt file.
What I need help on is to take the file name, add the FormattedDT (date/time) to it (original file name is FullFileName), then copy it over to an archive folder:
\\a70tsgnaeasa001\eas\server\log\archive
For example if the file name from the txt file it is reading from is:
\\A70TSGNAEASA001\d$\EAS\Server\FIPS\BCBSFIPS.TXT
and it was last modified 10/27/2017 at 3:00, then I would want the destination to be:
\\a70tsgnaeasa001\eas\server\log\archive\BCBSFIPS_10_27_2017_03_00_00.TXT
I am having trouble figuring out how to remove the .extension, appending the date/time of the file, and then copying it to the archive folder. I put the code I have so far below.
TXT File Format:
REM there is a comment here on the first line
\\filepath1
\\filepath2
...
\\filepathN
VBScript:
option explicit
Dim SFSO, f, WSSL, FullFileName, txtFile, exitCode, txtLine, ArchiveFolder,
DateFolder, CopyFileName
Dim ArchDT, FormattedDT, mon, day, yr, hr, min, sec, FileNameArray
ArchiveFolder = "\\\\A70TSGNAEASA001\\eas\\Server\\log\\Archive\\"
Set SFSO = CreateObject("Scripting.FileSystemObject")
Set WSSL = Wscript.CreateObject("WScript.Shell")
exitCode = 0
'tests for no args
If WScript.Arguments.Count = 0 then
WScript.quit (9999)
End If
txtFile = WScript.Arguments(0)
DateFolder = ArchiveFolder&Year(Date)&"-"&Month(Date)&"-"&Day(Date)&"\\"
SFSO.CreateFolder(DateFolder)
Set f = SFSO.OpenTextFile(txtFile)
On Error Resume Next
Do Until f.AtEndOfStream
txtLine = f.ReadLine
If(Left(txtLine,2) = "\\") Then
FullFileName = txtLine
' Check for file exists
If SFSO.fileexists(FullFileName) Then
' create archive folder path
'get modified date time, format to _mm_dd_yyyy_hh_mm_ss
ArchDT = CDate(SFSO.DateLastModified(FullFileName))
mon = Month(ArchDT)
day = Day(ArchDT)
yr = Year(ArchDT)
hr = Hour(ArchDT)
min = Minute(ArchDT)
sec = Second(ArchDT)
FormattedDT = "_"&mon&"_"&day&"_"&yr&"_"&hr&"_"&min&"_"&sec
' File name with date/time appended to it
FileNameArray = Split(FullFileName, "\")
ShortFileName = FileNameArray(UBound(FileNameArray))
FileNameArray2 = Split(ShortFileName, ".")
CopyFileName =
DateFolder&FileNameArray2(0)&FormattedDT&FileNameArray2(1)
'copy file to archive folder
SFSO.CopyFile FullFileName, CopyFileName
Else
'exitCode = 9999
End If
End If
Loop
f.Close
SFSO.Close
WScript.quit(exitCode)
I've made a few changes to the code just to let it read better as you had a few typos and the like in there.
I dropped a number of the variables as you had used a couple of reserved words (Day, Empty) and rejigged the ArchiveFolder as a constant.
The rest of the code is as per yours, until the else step. At that point I get the last modified date of the file in question (you were trying to use the SFSO object for this, but the object doesn't have that method available, so I used GetFile which does.
I split the date into the date and time elements, and reformatted as per your requirements, then joined the array back together to provide the formatted date value you want to append to the filename in the archive folder.
I then split the FullFileName variable that contains the file path on the "\" character and picked out the last element, which will contain the file name.
The CopyFileName is then constructed from the ArchiveFolder, and the archive file name, with the formatted date and ".txt" suffix replacing the existing filename suffix.
Let me know if you don't understand any of what I did and I'll try to explain further.
option explicit
Dim SFSO, WSSL, FullFileName, txtFile, exitCode, txtLine, CopyFileName
Dim ArchDT, FormattedDT, fileName, tempArray
Const ArchiveFolder = "\\A70TSGNAEASA001\eas\Server\log\Archive\"
Set SFSO = CreateObject("Scripting.FileSystemObject")
Set WSSL = Wscript.CreateObject("WScript.Shell")
exitCode = 0
'tests for no args
If WScript.Arguments.Count = 0 then
WScript.quit (9999)
End If
txtFile = WScript.Arguments(0)
Set f = SFSO.OpenTextFile(txtFile)
On Error Resume Next
Do Until f.AtEndOfStream
txtLine = f.ReadLine
If(Left(txtLine,2) == "\\")
FullFileName = txtLine
' Check for file exists
If SFSO.fileexists(FullFileName) then
' Check file status
If VarType(SFSO.OpenTextFile(FullFileName,8,False)) = vbError Then
exitCode = 9999
Else
ArchDT = oFso.GetFile(FullFileName).DateLastModified
'get modified date time, format to _mm_dd_yyyy_hh_mm_ss
tempArray = Split(ArchDT, " ") ' gives us an array with date and time in two elements
tempArray(0) = Right("0" & Month(ArchDT),2) & "_" & Right("0" & Day(ArchDT), 2) & "_" & Year(ArchDT)
tempArray(1) = Replace(tempArray(1), ":", "_")
FormattedDT = Join(tempArray, "_") ' now have the formatted date value
' Get the filename
tempArray = Split(FullFileName, "\")
fileName = tempArray(UBound(tempArray)) ' filename is the last element in this array
' File name with date/time appended to it
'Part I'm having trouble with
CopyFileName = ArchiveFolder & Replace(fileName, ".txt", FormattedDT & ".txt")
'copy file to archive folder (how I would copy the file)
SFSO.CopyFile(FullFileName, CopyFileName)
End If
Else
exitCode = 9999
End If
End If
Loop
f.Close
Err.Clear
SFSO.Close
WScript.quit(exitCode)

Update file name automatically within VBA

I have a excel file that is referenced in my macro that is named inventory report " today's date " ex. ( Inventroy report 11_01_2017) I was trying to find a way for VBA to always reference the file with the current date in its name
If you want to get the current file name, plus the current date, you can do:
Sub t()
Dim fileName As String, curDate As String
curDate = Date
fileName = ActiveWorkbook.Name
fileName = Left(fileName, InStr(fileName, ".") - 1)
fileName = fileName & " " & curDate
Debug.Print fileName
End Sub
If you need date with _ instead of / you can add:
curDate = WorksheetFunction.Substitute(date, "/", "_")

Resources