Excel VBA checking and comparing dates between workbooks - excel

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?

Related

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 search between two date ranges in VBA?

I have hit a stumbling block and could just do with some assistance please.
I have been tasked with creating a VBA Macro that looks between two date ranges in a shared inbox sub-folder in Outlook.
If the code finds any Excel documents attached to the emails within that date range it will extract the attachments and will put them into a designated shared drive folder. All of this i had working perfectly, however, I now need to change the code slightly so that on a separate sheet it adds the date the code was last ran (this I have working also) and when the code is next ran it takes the date it last ran as the "Date from" date and searches between that date and whatever the date and time is of the time you are trying to execute the code again - this is where my code isn't working.
Here is my code so far (I am not a VBA expert and some terminology may not be correct so please go easy on my code) - I have had to replace certain sensitive info with "xxxxxx" in the code below.
Sub saveOutlookAttachments()
' For this to work, you need to ensure "Microsoft Office 16.0 Object Library" is ticked
' You can find the object library in Tools -> References
' -- start of initialise all the outlook library details needed
Dim ol As Outlook.Application
Dim ns As Outlook.Namespace
Dim fol As Outlook.Folder
Dim i As Object
Dim mi As Outlook.MailItem
Dim at As Outlook.attachment
Dim Folder As MAPIFolder
Dim OutlookMail As Variant
' -- end of initialise all the outlook library details needed
' -- start of Date from and to initialising
Dim DateStart As Date
Dim DateEnd As Date
Dim DateToCheck As String
' Get the date last ran
If Sheet2.Cells(1, 2) <> "" Then
Sheet1.Cells(2, 2) = Sheet2.Cells(1, 2)
Debug.Print "Start Date is: "; Sheet1.Cells(2, 2)
Sheet1.Cells(2, 4) = Now()
Debug.Print "End Date is: "; Sheet1.Cells(2, 4)
Else
Sheet2.Cells(1, 2) = ""
Debug.Print Sheet1.Cells(2, 2)
End If
DateStart = Sheet1.Cells(2, 2) ' Cell B2
DateEnd = Sheet1.Cells(2, 4) ' Cell B4
DateToCheck = "[ReceivedTime] >= """ & DateStart & """ And [ReceivedTime] <= """ & DateEnd & """"
Debug.Print "Date to Check is: "; DateToCheck
' -- end of Date from and to initialising
' -- start of Set ol and Set ns
Set ol = New Outlook.Application
Set ns = ol.GetNamespace("MAPI")
' -- end of Set ol and Set ns
' Which folder should the script be reading from?
Set fol = ns.Folders("~ xxxxxxx ").Folders("Inbox").Folders("xxxxxxxx")
' if there is an error when the code runs then stop the script and go straight to "errordetails" found at the bottom of the screen
On Error GoTo errordetails
' For each email in the folder (Restricted to the date range entered on the Spreadsheet)
For Each i In fol.Items.Restrict(DateToCheck)
' If the email is an Outlook email
If i.Class = OlMail Then
Set mi = i
UserForm1.Show
' If there are more than 0 attachments, ie, if it finds an attachment
If mi.Attachments.Count > 0 Then
For Each at In mi.Attachments
'Debug.Print mi.SenderName & " " & mi.ReceivedTime ' <- uncomment this part if you need to debug (remember to open the "immediate" window also
' Look for attachments that contain ".xls" (this will also pick up ".xlsx" and ".xlsm" etc
If InStr(LCase(at.FileName), ".xls") > 0 Then
' Tell the script where to save the file and what details need to be appeneded to the file name to make it a unique name
at.SaveAsFile "\\xxxx\xxxxx\xxxxx\" & Format(mi.ReceivedTime, "yyyy-mm-dd hh-nn-ss") & at.FileName
Else
' literally do nothing (it's probably not needed but added just in case)
End If
Next at
End If
End If
Next i
UserForm1.Hide
CountNumberOfFiles
Sheet2.Cells(1, 1) = "Date last ran was"
Sheet2.Cells(1, 2) = Now()
errordetails:
Debug.Print "Error number: " & Err.Number _
& " " & Err.Description;
End Sub
Sub CountNumberOfFiles()
Dim FolderPath As String
Dim Path As String
Dim Count As Integer
FolderPath = "\\xxxx\xxxxxxx\xxxxxxxxx"
Path = FolderPath & "\*"
FileName = Dir(Path)
Do While FileName <> ""
Count = Count + 1
FileName = Dir()
Loop
MsgBox "Search completed. There are " & Count & " attachments extracted to the folder \\xxxxxx\xxxxxx\xxxx"
End Sub
In the Immediate window, the Debug.Print for this part does show all the correct dates and times but it says it finds nothing even when there is one item that definitely matches.
' Get the date last ran
If Sheet2.Cells(1, 2) <> "" Then
Sheet1.Cells(2, 2) = Sheet2.Cells(1, 2)
Debug.Print "Start Date is: "; Sheet1.Cells(2, 2)
Sheet1.Cells(2, 4) = Now()
Debug.Print "End Date is: "; Sheet1.Cells(2, 4)
Else
Sheet2.Cells(1, 2) = ""
Debug.Print Sheet1.Cells(2, 2)
End If
DateStart = Sheet1.Cells(2, 2) ' Cell B2
DateEnd = Sheet1.Cells(2, 4) ' Cell B4
DateToCheck = "[ReceivedTime] >= """ & DateStart & """ And [ReceivedTime] <= """ & DateEnd & """"
Debug.Print "Date to Check is: "; DateToCheck
' -- end of Date from and to initialising
Thank you in advance for any assistance provided.
Dates are DateTime, not Text, so create text expressions for the date values:
DateToCheck = "[ReceivedTime] >= #" & Format(DateStart, "yyyy\/mm\/dd") & "# And [ReceivedTime] <= #" & Format(DateEnd, "yyyy\/mm\/dd") & "#"
Addendum:
Looking up the docs (always highly recommended), it appears that criteria must be text:
Although dates and times are typically stored with a Date format, the
Find and Restrict methods require that the date and time be converted
to a string representation. To make sure that the date is formatted as
Outlook expects, use the Format function. The following example
creates a filter to find all contacts that have been modified after
January 15, 1999 at 3:30 P.M.
Example:
sFilter = "[LastModificationTime] > '" & Format("1/15/99 3:30pm", "ddddd h:nn AMPM") & "'"
So, I guess you filter should read:
DateToCheck = "[ReceivedTime] >= '" & Format(DateStart, "ddddd h:nn AMPM") & "' And [ReceivedTime] <= '" & Format(DateEnd, "ddddd h:nn AMPM") & "'"

Excel VBA Saving with Variable Name

Soo.... having a problem saving the excel with as the name i want it to generate.. it keeps saving as "FALSE"... from what i can tell I have everything correct. Since the directory will be a variable I rather just have it save in the current folder.
Ultimately I want it as Week # m-d-yy Site.xlsm
e.i Week 36 9-5-20 41st HMU
Sub SaveWorkBook()
Dim wb As Workbook
Dim myFile As String
Dim dDate As Date
Dim sSite As String
dDate = Date 'Todays date
sSite = Range("Q10").Value 'Site Name
myFile = "Week " & WorksheetFunction.WeekNum(dDate, 2) & Format(dDate, "m-d-yy") & " " & sSite & ".xlsm"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName = myFile
End Sub

how to open file with yesterday's workday in title

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

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