Access need to not overwrite reports - ms-access-2007

What is happening here is the report is overriding daily. How can I make the output name unique perhaps with a date? so it will not get deleted each time?
Public Function RunDMR()
'E:\Management Reports
Dim myfile As String
myfile = "E:\Management Reports\B3-Daily Fiscal Report on Net Estimated to Receive by Ins - 45.pdf"
DoCmd.OutputTo acOutputReport, "B3: Daily Fiscal Report on Net Estimated to Receive by Ins - 45", acFormatPDF, myfile, False
End Function

To add a date to the report name, use the following:
myfile = "E:\Management Reports\B3-Daily Fiscal Report on Net Estimated to Receive by Ins - 45_" & format(date,"YYYYMMDD") & ".pdf"
To add a date & time to the report name, use the following:
myfile = "E:\Management Reports\B3-Daily Fiscal Report on Net Estimated to Receive by Ins - 45_" & format(Now(),"YYYYMMDD_HHMMSS") & ".pdf"

Related

Trying to Find Duplicate Records in Access Error

I am making a databse for a sports club,
When filling out a form, they input the facility ID, start time, end-time and date.
What I am trying to do is when they enter the end time box, the function scans through the entries on the 'Bookings' Table where all the data from this form is stored, to see if the facility is booked out at this time. ( For dtermining if it is booked out at a certain time, if the start time or the end time on table is between what is filled in on the form, an error is thrown
The code is shown below:
Private Sub EndNon_AfterUpdate()
Dim criteria As String
criteria = _
"Non-PlayingFacilityID= " & Me.NonPlayID.Value & " " & _
"Date(Non-PlayingFacility)= " & Me.DateNon.Value & _
" " & "AND [StartTime(Non-PlayingFacility)] Between Me.StartNon.Value And Me.EndNon.Value OR [EndTime(Non-PlayingFacility)] Between Me.StartNon.Value And Me.EndNon.Value "
If DCount("*", "Bookings", criteria) > 0 Then
MsgBox "Unfortunately, this facility is booked at this time"
Me.Undo
End If
End Sub
Syntax error is thrown when I run this, not sure why.
Any help would be much appreciated
It probably highlights this invalid syntax:
"Date(Non-PlayingFacility)= " & Me.DateNon.Value & _
Perhaps you mean:
"DateValue([Non-PlayingFacility])= " & Format(Me!DateNon.Value, "\#yyyy\/mm\/dd\#") & _
The remaining date comparisons need to be concatenated and formatted similarly.
Addendum - given the obscure field name:
"[Date(Non-PlayingFacility)]= " & Format(Me!DateNon.Value, "\#yyyy\/mm\/dd\#") & _
The format is needed to create a valid string expression in SQL for the date value. This is independent of a format applied for display.

Looking for a custom solution to copy data from one workbook to another

I am trying to simplify a process for field employees at my work. The baseline case is that the employees fill out Daily Detail Reports in a single Excel Workbook throughout the year with the hours they have worked that day, the project # and Phase Code their labor costs will hit and the hours that they worked that day on that particular project. It is very common for the same project number and phase code to be used more than once for a single day (i.e. multiple row entries which will need the total hours added together based on the condition of having the same project number and phase code for that day). See attached "Detail Report WB" image.
Our employees then have to enter the same data in a different format (i.e. only one line allowed per project number and phase code pair per day) in a separate workbook. See attached "Timesheet Import WB" image. The timesheet workbook is driven based on the week end date for that week (i.e. Sunday). The Daily Detail Report workbook however, is driven based on the week beginning date and Sundays are not included in the Daily Detail Report. To make things more complicated, the dates listed in the Daily Detail report are based on formulas and do not house the actual date value in the cells.
The goal of this solution is to take the information entered into the Daily Detail Report workbook and place it into the Timesheet workbook via a sub function based on a ActiveX command button click event. See the attached “End Goal” image.
So far I have compiled the following code to allow the user to click the import button which prompts the user to find the Daily Detail Report workbook that they would like to import data from. This code also allows for the user to input the week end date desired for the Timesheet workbook. I was trying to use the week end date to find the desired data in the Daily Detail Report workbook, but this is proving difficult. Any assistance would be greatly appreciated. It’s been years since I took into to computer programming in VBA back in college.
Images are located here: https://drive.google.com/drive/folders/0B7BjXxM59FFyQlM5eThvc0dDWUU?usp=sharing
Thanks!
Private Sub CommandButton1_Click()
'Define All Variables
Dim GCell As Range
Dim fDialog As FileDialog, result As Integer
Dim MyDetailReport As String
Dim MyTimeSheet As String
Dim MySheet As String
Dim ProjNum As String
Dim PhaseCode As String
Dim Hours As String
Dim WkEndDate As String
'Find source file
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
fDialog.AllowMultiSelect = False
fDialog.Title = "Select Daily Report File to Import"
fDialog.InitialFileName = "W:\PDX - Mechanical Construction\Operations\Detailing\Daily Tracking Logs\"
fDialog.Filters.Clear
fDialog.Filters.Add "Excel files", "*.xlsx"
If fDialog.Show = -1 Then
MyDetailReport = fDialog.SelectedItems(1)
End If
'Enter date to look for in workbook
WkEndDate = InputBox("Insert Week End Date in format mm/dd/yyyy", "User date", Format(Now(), "mm/dd/yyyy"))
If IsDate(WkEndDate) Then
WkEndDate = Format(CDate(WkEndDate), "mm/dd/yyyy")
'Place Week End Date into Timesheet workbook
With ThisWorkbook.ActiveSheet.Range("AE5")
.Value = WkEndDate
End With
Else
MsgBox "Wrong date format"
End If
'Use the current sheet to store found data
MySheet = ActiveSheet.Name
'Use Error Handling routine in case of errors
On Error GoTo ErrorHandler
'Turn off screen updating to run macro faster
Application.ScreenUpdating = False
Workbooks.Open Filename:=MyDetailReport & MyTimeSheet
'Search Detail Report "Daily Report Log" sheet for the selected Week End Date
Set GCell = ActiveSheet.Cells.Find(WkEndDate, LookIn:=xlValues)
GCell = GCell.Offset(2, 1)
If GCell.Value = "" Then
GCell = GCell.Offset(1, 0)
Else
'copy data formulas to correct format for Timesheet workbook
End If
'Error Handling
ErrorHandler:
Select Case Err.Number
'Common error #2: the specified data wasn't in the target workbook.
Case 9, 91
Application.ScreenUpdating = True
MsgBox "The value " & WkEndDate & " was not found."
Exit Sub
'General case: turn screenupdating back on, and exit.
Case Else
Application.ScreenUpdating = True
Exit Sub
End Select
End Sub

VBA that imports data meeting certain criteria from all spreadsheets in a directory

This the following code that I have:
Public Function Import_Multi_Excel_Files()
Dim InputFile As String
Dim InputPath As String
InputPath = "L:\Directory\To\Project\Data\"
InputFile = Dir(InputPath & "*.xls*")
worksheetName = "WorksheetThatHasData!A:H"
Do While InputFile <> ""
DoCmd.TransferSpreadsheet acImport, , "Table_1", InputPath & InputFile, -1, worksheetName, True '< The true is for column headers
InputFile = Dir
Loop
End Function
The above code is grabbing all of the data from a specific worksheet within each workbook (which is good) and importing it into MS Access. But I noticed that our reports always include the current month and previous month even though the report is dated for the current month. Every file name has the format Report - YYYYMM. The idea I'm kicking around is something that will look at the YYYYMM portion of the file name and only grab the data with that corresponding date.
Edits and Additions Below
Actuarial_Report-201705
Enrollment_Report-201705
Premium-Data-201705
Each of the above reports includes information from May AND April. But the previous months report will clearly include data from April but also March, and so on. What's happening is that all the data I've imported counted enrollment, premium, and actuarial info twice. I want to only pull 201705 data from the 201705 reports and have the code ignore the 201704 info.
Replace your While loop with the following:
Dim strMonth As String
Dim strYear As String
Do While InputFile <> ""
strMonth = Mid(InputFile, Len(InputFile) - 6, 2)
strYear = Mid(InputFile, Len(InputFile) - 10, 4)
DoCmd.TransferSpreadsheet acImport, , "Table_1", InputPath & InputFile, -1, worksheetName, True '< The true is for column headers
CurrentDb.Execute "DELETE * From Table_1 WHERE MyDateColumn < #" & strYear & "/" & strMonth & "/01#"
InputFile = Dir
Loop
Where MyDateColumn is the column where you store dates.
Assumptions: You are not storing any other old information in Table_1 that you want to keep, else you would want to import to another table, remove the invalid date info, and then append the data to Table_1
The end of the file name cannot change, else this will generate bugs.
Note that I'm not using parameters in my query, but since the string is from a filename and has a max length of 6 with a / in the middle, the risk of SQL injection is not present.

Pick date from cell and use as a file handle while saving

A2=201604
I am trying to pick up value from a Cell(Date) and use the same for saving the file.
But while saving instead of the date a value is being printed, see code below:
Dim part1 as string
part1 = Range("A2").Value
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & "\xxx- " & Format(part1, "MMM-YYYY") & ".xlsx" , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
201604 is not a date. It is just a number.
You could use something like
myDate = "01/" & right(a2,2) & "/" left(a2,4)
string yourAnswer = format(myDate, "MMM-YYYY")
The problem is you're prematurely casting the Date into a String by using the part1 variable, so the 'date' is already broken and not recognisable as a date by the time it hits your Format() call.
Either declare part1 as a Date or just skip the whole part1 declaration and insert Range('A2').Value directly into the Format() call.

Stored procedure which has four input parameters

I have a stored procedure which has 4 input parameters.
#Scenario, #StockID, #EOD, #EOD_PREV.
Based on the #Scenario (total 9 Scenarios), different SQL scripts are executed.
My requirement is:
I need to use VB Macros to display results in each worksheet, I need to use one ActiveX-Command button to run all the Scenarios.
Each Scenario in a separate Worksheet.
So far, I have managed to create individual connections for each sheet and Active X Command Button for each sheet.
Below is the query that I used.
Private Sub CommandButton1_Click()
Dim Scenario As String
Dim STOCK_ID As String
Dim EOD As String
Dim EOD_PREV As String
Scenario = Sheets("Stocks").Range("B3").Value
STOCK_ID = Sheets("Stocks").Range("B8").Value
EOD = Sheets("Stocks").Range("B6").Value
EOD_PREV = Sheets("Stocks").Range("B7").Value
With ActiveWorkbook.Connections("9").OLEDBConnection
.CommandText = "EXEC dbo.usp_Inventory_Reconcilliation '" & Scenario & "','" &
STOCK_ID & "', '" & EOD & "' ,'" & EOD_PREV & "'"
ActiveWorkbook.RefreshAll
End With
End Sub
Can somebody help me out with this situation.
Get the ActiveWorkbook.RefreshAll out of the With, and maybe it'll be easier to use connections without VBA and just use it for your refresh button.