how to open file with yesterday's workday in title - excel

i need to open a file with yesterday's workday in the title and i have no idea how to do it.
Eg Monday (2nd sep) today, open Friday's (30th Aug) spreadsheet.
The spreadsheet title is a follows - "cash 300819"
I have tried the following code but doesnt seem to work
Dim wbO As Workbook, wbN As Workbook
Set wbO = ActiveWorkbook
Set wbN = Workbooks.Open("\\y:cash " & Format(CStr(Date)-1, "dd") & CStr(Format(Date, "mm")) & Right(CStr(Year(Date)), 4) & ".xlsx")
It will open previous working day's spreadsheet properly

You can use the DateAdd function in VBA to subtract a day, like this:
sFilename = "\\y:cash " & Format(DateAdd("d", -1, Date), "dd") & Format(Date, "mm") & Right(Year(Date), 2) & ".xlsx"
And you dont need the CStr function, as the format and right functions already return strings.
But what about the first day of the month?
It would be better to do it like this:
sFilename = "\\y:cash " & Format(DateAdd("d", -1, Date), "ddmmyy") & ".xlsx"
Alternatively, you can have a function that would return an empty string if no file was found, or return the filename of the most recent file based on your criteria, like this:
Public Function GetMostRecentFileByDate(dtStart As Date, sPath As String, sPrefix As String, sExt As String, sFormat As String) As String
Dim nDay As Integer
Dim sFilename As String
Dim dtDate As Date
Dim sFull As String
dtDate = dtStart
For nDay = -1 To -7 Step -1
sFilename = sPrefix & Format(dtDate, sFormat) & "." & sExt
sFull = sPath & "\" & sFilename
If Dir(sFull) <> "" Then
GetMostRecentFileByDate = sFull
Exit Function
End If
dtDate = DateAdd("d", -1, dtDate)
Next
End Function
Usage:
sFullName = GetMostRecentFileByDate("03 Sept 2019", "\\y:", "cash ", "xlsx", "ddmmyy")
If sFullName <> "" Then
' Do Something With It
End If

Related

Saving a Excel sheet

So i have found 2 macros which i want to use to save and create a back up files for the said file.
The Macro which i want to primarily use is this one:
Sub DateFolderSave()
Dim strGenericFilePath As String: strGenericFilePath = "D:\"
Dim strYear As String: strYear = Year(Date) & "\"
Dim strMonth As String: strMonth = MonthName(Month(Date)) & "\"
Dim strDay As String: strDay = Day(Date) & "\"
Dim strFileName As String: strFileName = "_Dispatch Process_"
Application.DisplayAlerts = False
' Check for year folder and create if needed
If Len(Dir(strGenericFilePath & strYear, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear
End If
' Check for month folder and create if needed
If Len(Dir(strGenericFilePath & strYear & strMonth, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth
End If
' Check for date folder and create if needed
If Len(Dir(strGenericFilePath & strYear & strMonth & strDay, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth & strDay
End If
' Save File
ActiveWorkbook.SaveAs FileName:= _
strGenericFilePath & strYear & strMonth & strDay & strFileName, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Application.DisplayAlerts = True
' Popup Message
MsgBox "File Saved As: " & vbNewLine & strGenericFilePath & strYear & strMonth & strDay & strFileName
End Sub
So i found this another Macro which make continuous back up of the files and has a custom format to a file name
Sub Save_Backup(ByVal Backup_Folder_Path As String)
Dim fso As Object
Dim ExtensionName As String, FileName As String
Dim wbSource As Workbook
Set fso = CreateObject("Scripting.FileSystemObject")
Set wbSource = ThisWorkbook
ExtensionName = fso.GetExtensionName(wbSource.Name)
FileName = Replace(wbSource.Name, "." & ExtensionName, "")
fso.CopyFile ThisWorkbook.FullName, _
fso.BuildPath(Backup_Folder_Path, FileName & " (" & Format(Now(), "dd-mmm-yy hh.mm AM/PM") & ")." & ExtensionName)
Set fso = Nothing
Set wbSource = Nothing
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Call Save_Backup("C:\Users\admin\Downloads\Back Up\New Backup")
End Sub
So i want to create back up like the first macro(i.e. Folder inside a folders for the specific date) but want to have a continuous stream of files for back up(i.e. Want the date folder to create new save file each time i save the Document)
Is there a way to combine both these macros?

Spreadsheet fails to export to Access database when folder is not empty

I'm trying to export a spreadsheet to an Access database. I have three routines: one which creates an Access file with today's date, one which creates a connection with the database and another which imports the data to the Access file.
Everything works correctly when the folder of the dashboard is empty beforehand. However, when there is already another Access file in the folder, it does not export, displaying the following error message:
I couldn't find anything online which was relevant to this particular issue. Does anyone know why this is happening?
'creates an Access database
Sub CreateAccessDB()
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
'the path to create the new access database
Dim strPath As String
'an Access object
Dim objAccess As Object
date1 = Format(Date, "DD")
Year = Format(Date, "YYYY")
Month = Format(Date, "MM")
MonthChar = MonthName(Month, False)
'states the directory for our database
strPath = "Z:\Danny Tool Test Folder\Database\" & Year & "\" & _
Month & ". " & MonthChar & " " & Year & "\WeeklyActivity_" & date1 & Month & Year
'if the file already exists, we open it
If fso.FileExists(strPath & ".accdb") Then
Call OpenAccessDatabase(strPath & ".accdb")
'if the file does not exist, we create it
Else
Set objAccess = CreateObject("Access.Application")
Call objAccess.NewCurrentDatabase(strPath)
objAccess.Quit
Call OpenAccessDatabase(strPath & ".accdb")
End If
End Sub
Sub ADO_Connection_1()
date1 = Format(Date, "DD")
Year = Format(Date, "YYYY")
Month = Format(Date, "MM")
MonthChar = MonthName(Month, False)
'Creating objects of Connection and Recordset
Dim conn As New Connection, rec As New Recordset
Dim DBPATH, PRVD, connString As String
'Declaring fully qualified name of database. Change it with your database's location and name.
DBPATH = "Z:\Danny Tool Test Folder\Database\" & Year & "\" & _
Month & ". " & MonthChar & " " & Year & "\WeeklyActivity_" & date1 & Month & Year & _
".accdb"
'This is the connection provider. Remember this for your interview.
PRVD = "Microsoft.ace.OLEDB.12.0;"
'This is the connection string that you will require when opening the connection.
connString = "Provider=" & PRVD & "Data Source=" & DBPATH
'opening the connection
conn.Open connString
End Sub
'exports the data from the spreadsheet to the Access database
Sub ExportReport()
'declaring our files, directories, tables and field names
Dim strPathFile As String, strFile As String, strPath As String, FileName As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
Dim MasterDB As Worksheet
date1 = Format(Date, "DD")
'Declaring year value of 1 month
'This is important to compare datasets from last month
If date1 > 26 Then
Year_1M = Format(Date - 37, "YYYY")
Else
Year_1M = Format(Date - 27, "YYYY")
End If
'Declaring month value of 1 month
'This is important to compare datasets from last month
If date1 > 26 Then
Month_1M = Format(Date - 37, "MM")
Else
Month_1M = Format(Date - 27, "MM")
End If
'This translates the current month from number to character format
MonthChar_1 = MonthName(Month_1M, False)
'setting Account sheet as MASTERFILE & the date
sheet = "Overall Activity" & "!"
Application.DisplayAlerts = False
blnHasFieldNames = True
strPath = "Z:\Danny Tool Test Folder\"
strTable = "ActivityTable"
strFile = Dir(strPath & "Weekly Activity Reporting Tool.xlsm")
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames, sheet
Application.DisplayAlerts = True
End Sub
'function opens the Access database
Public Function OpenAccessDatabase(strPath As String)
If Not IsNull(strPath) Then Shell "MSACCESS.EXE """ & strPath & """", vbNormalFocus
End Function
(It fails at DoCmd.TransferSpreadsheet)
Try using the correct spreadsheet format:
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, _
strTable, strPathFile, blnHasFieldNames, sheet
AcSpreadSheetType enumeration (Access)
This simple procedure creates database if doesn't already exist then transfers data from Excel to database.
Sub ExcelToAccess()
Dim strDbPath As String
Dim strExFile As String
Dim strTable As String
Dim Sht As String
Dim objAccess As Object
Dim date1 As String, Yr As String, Mn As String
date1 = Format(Date, "DD")
Yr = Format(Date, "YYYY")
Mn = Format(Date, "MM")
Sht = "Sheet1!"
strTable = "Test"
strExFile = "C:\Users\Owner\June\MyStuff\Condos.xlsm"
strDbPath = "C:\Users\Owner\June\Forums\WeeklyActivity_" & date1 & Mn & Yr & ".accdb"
Set objAccess = CreateObject("Access.Application")
objAccess.Visible = False
If Dir(strDbPath) = "" Then
objAccess.NewCurrentDatabase(strDbPath)
Else
objAccess.OpenCurrentDatabase (strDbPath)
End If
objAccess.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, strTable, strExFile, True, Sht
End Sub

How do I use a cell value, assigned to a variable, in a filepath string?

I am trying to open an Excel spreadsheet within a changing location. The variables are the dates and file name:
C:\Reports\2019\09. September 2019\10 September 2019\1. Client reports\Report_20190911.csv
I have tried using variables, referencing to specific cells within a workbook to add the dates that are changing on a daily, monthly, and yearly basis.
Example:
Today - C:\Reports\2019\09. September 2019\10 September 2019\1. Client reports\Report_20190911.csv
Tomorrow - C:\Reports\2019\09. September 2019\11 September 2019\1. Client reports\Report_20190912.csv
I cannot seem to add an image of my referenced excel cells so I will describe it (all the cells are formula driven for the date):
Cell B4 - 10/09/2019
Cell B6 - 2019
Cell B7 - 09. September 2019
Cell B9 - 10 September 2019
Below is my code:
Sub Client_Reports()
Dim year_ As Integer
year_ = Cells(6, 2)
Dim month_ As String
month_ = Cells(7, 2)
Dim date_ As Date
date_ = Cells(9, 2)
Dim FilePath As String
Dim FileName As String
FileName = "Report_" & Format(Range("B4") + 1, "yyyymmdd") & ".csv"
FilePath = "C:\Reports\year_\month_\date_\1. Client reports\FileName"
Workbooks.Open (FilePath)
End Sub
It searches for C:\Reports\year_\month_\date_\1. Client reports\Report_20190911.csv
As stated in the comments you should write the following:
FilePath = "C:\Reports\" & year_ & "\" & month_ & "\" & date_ & "\1. Client reports\" & FileName
Never put a variable's name inside double quotes when you want to build a string expression. It's like typing its name as a string, you are not referencing to the actual variable.
This is how I'd do it:
Option Explicit
Sub Client_Reports()
Dim MyDate As Date
MyDate = ThisWorkbook.Sheets("MySheet").Range("B4") 'change MySheet to the sheet name holding the date
Dim MonthName As String
MonthName = Format(MyDate, "mmmm") 'this takes the month name
Dim MonthNumber As String
MonthNumber = Format(MyDate, "mm") 'this takes the month number with 2 digits
Dim DayNumber As String
DayNumber = Format(MyDate, "dd") 'this takes the day number with 2 digits, switch to "d" for 1 digit.
Dim FilePath As String
FilePath = "C:\Reports\" & Year(MyDate) & "\" & MonthNumber & ". " & MonthName & "\" & DayNumber & " " & MonthName & _
" " & Year(MyDate) & "\1. Client reports\"
Dim FileName
FileName = "Report_" & Format(MyDate, "yyyymmdd") & ".csv"
Dim wb As Workbook
Set wb = Workbooks.Open(FilePath & FileName)
End Sub
This way you only need the cell B4 everything else can be done just with that.

Excel VBA checking and comparing dates between workbooks

I've got an excel script that that checks and compare dates between cells in different workbooks.
I've got four workbooks, wbk, wbkA, wbkB, wbkC, and wbkD.
Date in last cell in Column A of wbk is used as reference date
Date in Cell A9 of the rest of the workbooks is checked against reference date to check that they are one day after reference date
results are written to a log file
The script should write all results to a log (whether date is ok or not) and should only continue when all dates are ok. Ohterwise it should write to the log file which dates are not ok and exit sub.
If possible I would like to be call comparebooks from other modules instead
My problem:
Date checks work individually but I'm having trouble getting the script to check for multiple dates without running into errors
I cannot get it to work together with the writing to the log
Script to check compare dates
Sub comparebooks()
Dim dateX As Date
Dim dateA As Date
Dim dateB As Date
Dim dateC As Date
Dim dateD As Date
sFilename = ThisWorkbook.Path & "\Logs.txt"
sPath = ThisWorkbook.Path & "\Source\"
sFile = Dir(sPath & "2G Voice*.xlsx")
sFile1 = Dir(sPath & "2G Data*.xlsx")
sFile2 = Dir(sPath & "3G*.xlsx")
sFile3 = Dir(sPath & "4G*.xlsx")
'reference date file 4G
Set wbk = Workbooks.Open(ThisWorkbook.Path & "\2G.xlsx")
Set varSheet = wbk.Worksheets("2G Voice")
dateX = wbk.Worksheets("2G Voice").Range("A" & Rows.Count).End(xlUp)
'file dates to check
Set wbkA = Workbooks.Open(sPath & sFile)
Set varSheetA = wbkA.Worksheets("Sheet1")
dateA = wbkA.Worksheets("Sheet1").Range("A9")
Set wbkB = Workbooks.Open(sPath & sFile1)
Set varSheetB = wbkB.Worksheets("Sheet1")
dateB = wbkB.Worksheets("Sheet1").Range("A9")
Set wbkC = Workbooks.Open(sPath & sFile2)
Set varSheetC = wbkC.Worksheets("Sheet1")
dateC = wbkC.Worksheets("Sheet1").Range("A9")
Set wbkD = Workbooks.Open(sPath & sFile3)
Set varSheetD = wbkD.Worksheets("Sheet1")
dateD = wbkD.Worksheets("Sheet1").Range("A9")
'check 4g date
If dateA = DateAdd("d", 1, dateX) Then
Debug.Print dateA & " 2G Voice is OK"
If dateB = DateAdd("d", 1, dateX) Then
Debug.Print dateB & " 2G Data is OK"
If dateC = DateAdd("d", 1, dateX) Then
Debug.Print dateC & " 3G CS_PS is OK"
If dateD = DateAdd("d", 1, dateX) Then
Debug.Print dateD & " 4G Data is OK"
Else
Debug.Print "Date is not OK"
End If
Exit Sub
End If
End Sub
Logbook script
' Archive file at certain size
If FileLen(sFilename) > 20000 Then
FileCopy sFilename _
, Replace(sFilename, ".txt", Format(Now, "ddmmyyyy hhmmss.txt"))
Kill sFilename
End If
' Open the file to write
Dim filenumber As Variant
filenumber = FreeFile
Open sFilename For Append As #filenumber
Print #filenumber, CStr(Now) & ", " & "Missing source file: " & strType & " is missing " & chknum - i & " file(s)"
Close #filenumber
End If
Can someone please assist?

How to save excel file with incrementing number?

I am looking for VBA to add to my macro that will increment the file name if the file name already exists.
Current Code:
Dim filepath As String
Dim filename As String
Dim filepatharch As String
Dim filedate As String
Dim filelist As String
'Grab FROM list number
Sheets("TD File").Select
Range("G4").Select
filelist = ActiveCell.Value
'Grab today's date
filedate = Format(Now, "MMDD01.") --------------Currently where the '01' comes from (see below)
'Set where to save and the file naming convention
filepath = "\\home\serverfolder\FileDrop\"
tdfilename = "TD" & filedate & filelist
'& ".txt"
'Set where to save and the file naming convention
filepatharch = "\\home\myfolder\archive"
tdfilename = "TD" & filedate & filelist
'& ".txt"
'Save THXXXXXX.XXX & TDXXXXXX.XXX as flat files
'Workbooks("MYWORK01").Activate
Sheets("TDflatfile").Copy
ActiveWorkbook.SaveAs filename:= _
"\\home\serverfolder\FileDrop\" & tdfilename, FileFormat:=xlCSV, _
CreateBackup:=False
ActiveWindow.Close
An example of the saved file name would be "TD101401.600". TD + MMDD + 01 + .XXX. I would like the "+ 01 " to be the number that increments, that way I could have a file that is "TD101402.600" and so forth. Currently if the file exists for the same .XXX number and date combo, it gets overwritten. The .XXX cannot be the increment.
Is this possible?
Someone suggested this and it worked for me:
Dim filecount As Integer
Do While Len(Dir(filepatharch & thfilename)) <> 0
filecount = filecount + 1
filedate = Format(Now, "MMDD0" & filecount & ".")
tdfilename = "TD" & filedate & filelist
thfilename = "TH" & filedate & filelist
Loop
Just put a conditional loop with Dir()
Do While ((Dir(filepath & tdfilename)) <> Empty)
inc = inc+1
filedate = Format(Now, "MMDD") & "." & Format(inc, "00")
tdfilename = "TD" & filedate & filelist
Loop

Resources