Refresh/Update/Requery an access Report daily with new data - vba

I am trying to write some VBA to update a report with the most current data daily from a table. This report collects all the data from this table and shows it in a presentable manner but I don't want it to grab previous days data, only update from 12:00am to 12:00pm for instance every day, then incorporate this with my code to export this report as a pdf (which already works, but just shows the whole table constantly). It should be possible as my report has dates that are stored as values, I just don't know how to go about it with If statements etc. Here is my code for a module that is connected to a macro that is automatically run daily.
Function Reportmacro()
On Error GoTo Reportmacro_Err
Dim fpath As String
' Check for year folder and create if needed
If Len(Dir("H:\TEST\" & Year(Date), vbDirectory)) = 0 Then
MkDir "H:\TEST\" & Year(Date)
End If
' Check for month folder and create if needed
If Len(Dir("H:\TEST\" & Year(Date) & "\" & MonthName(Month(Date), False), vbDirectory)) = 0 Then
MkDir "H:\TEST\" & Year(Date) & "\" & MonthName(Month(Date), False)
End If
' Check for day folder and create if needed
fpath = "H:\TEST\" & Year(Date) & "\" & MonthName(Month(Date), False) & "\" & Day(Date)
If Len(Dir(fpath, vbDirectory)) = 0 Then
MkDir fpath
DoCmd.OutputTo acOutputReport, "Changeover Car Report", "PDFFormat(*.pdf)", fpath & "\" & "CCReport" & Day(Date) & "_" & Month(Date) & "_" & Year(Date) & ".pdf", False, "", , acExportQualityPrint
End If
Reportmacro_Exit:
Exit Function
Reportmacro_Err:
MsgBox Error$
Resume Reportmacro_Exit
End Function
For some more background: My table includes a ChangeoverID, Formdate(a date that a corresponding form is completed then recorded in table), Formtime(same as form date but just time), CardID(card scanner id), EmployeeID, CarID, etc. I suppose the time here wont matter because I am aiming to get it reported daily, hopefully without changing the original table, just the report code?
Sorry for the confusion

The issue you're having is because your report itself is not filtered. Try changing the report itself to have a default filter of Formdate = Date -1, which I assume is how you are determining which information counts as "Yesterday."
The other alternative is to open the report with a WhereCondition, then output the open form, then close it. All of that can be done in VBA with a single function. If you need help writing that function, let me know and I'll edit this post.

Apologies guys, I have actually found a solution based on what most of you said. I ended up thinking about a filtering option for my report (especially since I just wanted to grab specifics without manipulating the raw data itself) Going into the report layout view I found the option to sort by date by right clicking the field and selecting one of the many options... "today" was one of them. Then I had the issue of this filter not being loaded on start up of the report... So I enabled that in the properties view which makes everything work as intended! Filter is loaded on startup, every day and the report is auto generated to save on a network share. Thanks for your help, it did lead me on the right track.

Related

VBA Excel ... How to leave latest 5 backups and delete rest?

I want to leave the latest 7 backups and delete the rest ...
& I want to keep the first backup of each Month ...
& The programm should OpenAsReadOnly the backups without asking!
Here is my code:
Option Explicit
Sub Workbook_Open()
If Dir(ActiveWorkbook.Path & "\" & "Backup", vbDirectory) = "" Then
MkDir (ActiveWorkbook.Path & "\" & "Backup")
End If
Dim Pfad As String
Dim Datumzeitstempel As String
Dim Jetzt As Date
Jetzt = Now()
Pfad = ActiveWorkbook.Path & "\" & "Backup"
Datumzeitstempel = Year(Date) & Format(Month(Date), "00") & Format(Day(Date), "00")
ActiveWorkbook.SaveCopyAs (Pfad & "\" & Datumzeitstempel & ".xlsm")
ReadOnlyRecommended = True
End Sub
To solve problem with backup rotation you can do following. Instead of writing files with month and day in it, use WEEKDAY function. Then you will overwrite daily backup every time you open your file leaving backups for last week / 7 days.
To solve monthly backup problem You can do same just by using month only. When new month comes the new backup will be started.
Only problem with this solution is that last backup will be overwritten every time you open your file.
If you really need first backup made, then you will have to check for file existence.
But maybe better solution will be to write a script external to your file and run backup on scheduled basis E.g. at midnight. It can even be vbscript you are familiar with.

What is the meaning of "No" in this line of code [VBA]

I am new to VBA programming and recently I have come accross this line of code at work and I couldn't find any answer for it from my colleagues, as none of them are coders.
S2_path = "\\wswvnascti0005\fin_pol_pcRegion\MENA\S2_reports\"
S2_file = "CEEMEA-StandardPLCEEMEA_with_daily-20" & year & month & day & ".csv"
folder_to = "\\wswvnascti0005\fin_pol_pcRegion\MENA\ALL\"
pnl_new = "MENA_Consolidated_PnL_20" & year & "-" & month & "-" & day & ".xlsm"
Application.Workbooks.Open S2_path & S2_file, No
The line of code that I'm talking about is the last line, where you can find the word No. What is the meaning of that word in this case?
Thanks for help guys and sorry for my English!
It's (incorrectly) saying not to update links (UpdateLinks) - should say False here.
The parameters as delineated by commas (as per below) and because it's after the first comma, it's related to UpdateLinks.
Another way that code could have been written would be Application.Workbooks.Open S2_path & S2_file, UpdateLinks:=False

How to set a filepath in VBA that will vary based on the month?

I'm having an issue. Currently I have a couple vb modules working off one another that when executed will increment a drop down list, save a version of each option on the drop down list, and print out a copy as well.
Right now I'm using this filepath.
Sub G5()
'Update 20141112
Dim Path As String
Dim filename As String
Path = "C:\Users\MY.Name\Documents\Testing\" & _
Range("G5") & "\"
filename = Range("G5")
If ActiveSheet.Range("G5").Value = "" Then End
If ActiveSheet.Range("G5").Value = "NAMES" Then Exit Sub
ActiveWorkbook.SaveAs filename:=Path & filename & "-" & Format(Date, "mmddyyyy") & ".xlsm", FileFormat:=52
End Sub
So cell G5 contains the name (Last, First) of the person whose voucher this is. Each name is data validated and is identical to the name of their individual folder. Currently the script will save to their folder, but within those folders are 12 sub folders, one for each month. Is there any way for me to get the files to save into the correct month folder?
Cell I10 is the only cell that mentions the month by name, but in the format of "June Transit Reimbursement"
Any help would be appreciated. The script above runs in conjunction with two others, and although its doing 95% of what I need it to do, if I can get past this final hurdle the process will be 100% automated.
I'm trying to read through Like Operators and Option Compare Statements, but I'm struggling, and after reading so many posts here am hoping someone can help
Get the month by taking the first word from I10 and then put it in the file path assuming your folders use the same name formats that show up in I10.
parts = Split(Range("I10"), " ")
theMonth = parts(0) & " " & parts(1)
Path = "C:\Users\MY.Name\Documents\Testing\" & Range("G5") & "\" & theMonth & "\"
Updated to use first 2 words from cell using Mat's Mugs comments.

Linking multiple Excel documents to an Access DB

I have ~200 Excel workbooks each with a unique name, in its own folder, something like C:\docs\daily\XXXX\XXXX_Daily_Report_20150920.xls, where XXXX is just an alphanumeric identifier and the date is obviously just today's date.
I need to get one cell (the same cell, "I2") from all 200+ Excel workbooks every single day.
I know you can link Excel workbooks to Access but I can't figure out a way to make it link to a different workbook each day and I'm wondering if there is a query to simply get that one cell instead of linking the entire Excel workbook.
Right now I have Excel VBA that opens each Excel file and copies and pastes it into the corresponding row/column in my workbook...but since it does this 200+ times I'm wondering if Access will have a faster solution.
Is there any way to write a query/macro in Access that will link the cell I2 from each day's new report (so tomorrow's would be "XXXX Daily Report 20150921.xls") and just populate a table with XXXX in the first column and the value of I2 in the second?
Function import()
source_date = InputBox("date (yyyymmdd)")
Set db = CurrentDb()
db.Execute ("delete * from [DailyData]")
Set app = CreateObject("Excel.Application")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set folder_list = FSO.GetFolder("C:\docs\daily").subfolders
For Each Fldr In folder_list
Source = Fldr.Name
SourceFile = "c:\docs\daily\" & Source & "\" & Source & "_daily_reports_" & source_date & ".xlsm"
Set WB = app.workbooks.Open(SourceFile)
amount = WB.sheets("sheet1").range("I2").Value
SQL = "Insert into [DailyData] (source, amount) select '" & Source & "'," & amount
db.Execute (SQL)
WB.Close
Next Fldr
MsgBox ("done")
End Function
This takes all the files for a specific date and puts the input into a table called DailyData, with fields for Source and Amount.
Note - modified 9/22 to eliminate the inside loop and If block - this assumes every folder will have a file for the current day's update. If not, you may want to verify that the file exists before you try to open it.

How to pull data into excel from access?

I have an excel worksheet that has two sheets. On the first one i have the printable page and the second sheet is for the first to pull data from using vlookup. The second sheet consists of 8 columns. The first column is the ID that's being used by vlookup on the first page. The second is for first/last name. What i want to do is to make excel search for this (first/last name) in an access database and then retrieve and fill 3 other columns from the data in access. There are 2 tables that i want it to look into. It will find the name in either one of them and there are no duplicates. Does anyone have any idea how i might achieve this? Thanks!
You have a few choices. One is to use an .ODC using "Data-Get External Data". If you go through the wizard you can store the search criteria in the external data link (and if desired save this as an .ODC file). If you record a Macro when doing this, you will see where you can alter the recorded VBA code to substitute your own criteria from Excel (e.g, First/Lame name).
Another way, if your data isn't too big is to bring in a single sheet with "Data-GetExternalData" containing all your data then use VLookup (or index/match) to just retrieve the appropriate names. This works well when your database is not too big to bring entirely into Excel, efficiently.
But I use the following code because it's slick and doesn't require exposing any connection info (including passwords) in the .ODC (stored external data link). It's also faster. In this example, I use ADO because it's a SQL/Server database, but if the data is in Access (.ACCDB or MDB) then you can use ordinary DAO. If you need the ADO, don't forget to include the ADO library in your references.
In my example, I used a date range to find the data I wanted. In your case, it would be Lname and Fname instead of a date range.
This Excel VBA code is what I use.
Sub RefreshReport()
On Error GoTo Err_Handler
verrevent = "RefreshReport"
Dim rs As New ADODB.Recordset
If cn.State = 0 Then OpenNewConnection
Dim xlRange As Excel.Range
'Delete prior data
Range("MyTargetTable").EntireRow.Delete
'Call sproc to fetch member match
'This uses SPROC, but could be any SQL statement passing search criteria from Excel
vsql = "sproc_my_procedure '" & Range("BegDate") & "' ,'" & Range("EndDate") & "'"
'Call sproc to fetch member match
Set xlRange = Range("MyTargetDataSheet!A2")
Set rs = cn.Execute(vsql)
xlRange.Cells.CopyFromRecordset rs
'Refresh a pivot table if you have one
Set pt = Sheets("Summary").PivotTables("PivotTable1")
pt.RefreshTable
MsgBox ("Refresh Complete")
Exit_Proc:
Exit Sub
Err_Handler:
MsgBox ("Refresh program error. Please snip and send." & vbCrLf & vbCrLf & "Err " & Err.Number & " " & verrevent & " " & vbCrLf & Err.Description & vbCrLf)
Resume Exit_Proc
End Sub