MS Access VBA and Macro to Export - ms-access

I have a MS Acccess 2013 Database with many stored queries and linked tables to Excel spreadsheets. There are 3 in particular I need to export and I need to create backups as well. In my attempt to automate it, I am trying to use VBA.
Query Names:
query1
query2
query3
The DB is located in \\Reports\Run\Data
I would like BOTH the first and second query to export to both \\Reports\Type1\ and \\Reports\Type1\[new sub-folder 1]
I would like the third query to export to both \\Reports\Type2\and \\Reports\Type2\[new sub-folder 2]
One of the linked Excel spreadsheets (Table Name = Sheet1) has 1 single field and 1 single entry, which is the ReportDate. I would like both [new sub-folder 1] and [new sub-folder 2] to be that single date entry. For example, if 2019-03-06 was the entry, both sub-folders should be called "2019-03-06". These are my backup and stored copies.
The export should overwrite the existing files in \\Reports\Type1 and \\Reports\Type2.
It would be nice to be able to prefix the names the files in the new sub-folders with the ReportDate as well if possible.
So the final result would then be
\\Reports\Type1\2019-03-06\20190306_query1.xlsx,
\\Reports\Type1\2019-03-06\20190306_query2.xlsx and
\\Reports\Type2\2019-03-06\20190306_query3.xlsx as an example.
I created a macro to export and converted it to VBA as a starting point. However, I am not sure how to do the dynamic naming and changing the path dynamically of the export.

Here is the code I used. I hope it helps someone else!
Option Compare Database
Option Explicit
Public Function ExportExcel()
'Declare all variables
Dim file As Object
Dim filepath As String
Dim fp_report1 As String
Dim fp_report2 As String
Dim fp_report1_date As String
Dim fp_report2_date As String
Dim data1 As String
Dim data2 As String
Dim data3 As String
Dim fp_report1_data1 As String
Dim fp_report1_data2 As String
Dim fp_report2_data3 As String
Dim fp_reportdate As String
Dim reportdate_backup As String
Dim reportdate As String
Dim data1_run As String
Dim data2_run As String
Dim data3_run As String
Dim myVar As Date
'Get report date from the ReportDate linked table
myVar = DLookup("ReportDate", "tbl_reportdate", "ReportDate")
' Get current path
filepath = CurrentProject.Path
'Destination for files for dashboard
fp_report1 = Left(filepath, 87) & "\report1\"
fp_report2 = Left(filepath, 87) & "\report2\"
'Location for backup with the date as the folder name
fp_report1_date = Left(filepath, 87) & "\report1\" & Format(myVar, "yyyy-mm-dd")
fp_report2_date = Left(filepath, 87) & "\report2\" & Format(myVar, "yyyy-mm-dd")
'Location of raw reports to backup and date file
fp_report1_data1 = Left(filepath, 97) & "report1_data1.xls"
fp_report1_data2 = Left(filepath, 97) & "report1_data2.xls"
fp_report2_data3 = Left(filepath, 97) & "report2_data3.xls"
fp_reportdate = Left(filepath, 97) & "ReportDate.xlsx"
'If the folders for the backup doesn't exist, create it, otherwise, do nothing.
If Dir(fp_report1_date, vbDirectory) = "" _
Then MkDir (fp_report1_date) _
Else _
If Dir(fp_report2_date, vbDirectory) = "" _
Then MkDir (fp_report2_date) _
Else _
'Exact path with file name for backup of processed data in the appropriate date folder
data1 = fp_report1_date & "\" & "data1.xlsx"
data2 = fp_report1_date & "\" & "data2.xlsx"
data3 = fp_report2_date & "\" & "data3.xlsx"
reportdate_backup = fp_report1_date & "\" & "ReportDate.xlsx"
'Exact path with file name for dashboard to automatically pull
data1_run = fp_report1 & "data1.xlsx"
data2_run = fp_report1 & "data2.xlsx"
data3_run = fp_report2 & "data3.xlsx"
reportdate = fp_report1 & "ReportDate.xlsx"
'Export queries into the date backup folder
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "data1", data1
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "data2", data2
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "data3", data3
'Copy the files from the date backup folder into the path to be used by the dashboard. This includes the raw data in the reports and all the processed reports
FileCopy data1, data1_run
FileCopy data2, data2_run
FileCopy data3, data3_run
FileCopy fp_report1_data1, fp_report1_date & "\" & "report1_data1.xls"
FileCopy fp_report1_data2, fp_report1_date & "\" & "report1_data2.xls"
FileCopy fp_report2_data3, fp_report2_date & "\" & "report2_data3.xls"
FileCopy fp_reportdate, reportdate_backup
FileCopy reportdate_backup, reportdate
End Function

Related

Display Pdf preview in Ms Access Report using pdf file path

I am new in MS Access. I have pdf file location in textbox. I want when access report load then specific pdf file preview in that report (pdf read from file location). How can I achieve it? Please help?
You can display PDF in Report by converting its pages to images and display them. Withwsh.Runyou can extract duringReport_Loadevent, then store the pages paths in a temporary table.
Have Irfanview with PDF-Plugin installed.
In Front-End, create a table namedTmpExtractedPageswith oneShort-Textfield namedPathto store the paths of the extracted pages.
Create a report with Record-Source.
SELECT TmpExtractedPages.Path FROM TmpExtractedPages;
Add a Picture-Control in Detail-Section (no Header/Footer-Section), that fits to the page and bind it toPath
Put the following code inReport_Loadevent
Private Sub Report_Load()
Dim TempPath As String
TempPath = CurrentProject.Path & "\TempPdf"
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FolderExists(TempPath) Then
fso.DeleteFolder TempPath
End If
fso.CreateFolder TempPath
Dim PdfFile As String
PdfFile = Me.OpenArgs
Const PathToIrfanView As String = "C:\Program Files (x86)\IrfanView\i_view32.exe"
Dim CmdArgs As String
CmdArgs = Chr(34) & PdfFile & Chr(34) & " /extract=(" & Chr(34) & TempPath & Chr(34) & ",jpg) /cmdexit" 'see i_options.txt in IrfanView folder for command line options
Dim ShellCmd As String
ShellCmd = Chr(34) & PathToIrfanView & Chr(34) & " " & CmdArgs
Debug.Print ShellCmd
Dim wsh As Object
Set wsh = CreateObject("WScript.Shell")
Const WaitOnReturn As Boolean = True
Const WindowStyle As Long = 0
wsh.Run ShellCmd, WindowStyle, WaitOnReturn
With CurrentDb
.Execute "Delete * From TmpExtractedPages", dbFailOnError
Dim f As Object
For Each f In fso.GetFolder(TempPath).Files
.Execute "Insert Into TmpExtractedPages (Path) Values ('" & Replace(f.Path, "'", "''") & "');", dbFailOnError
Next f
End With
Set fso = Nothing
Set wsh = Nothing
End Sub
You provide the path to the PDF to display asOpenArgsargument on open report:
DoCmd.OpenReport "rpt_pdf", acViewPreview, , , , "path\to\pdf"
Keep in mind that adding, then deleting records to the temp table, will bloat your database if you don't compact it later (or just deploy a fresh Front-End copy on start, as I do).
If you just need to display the pdf file, you could create a button next to the textbox and in its on click event:
Private Sub cmdView_Click()
If Nz(Me.txtPdfLocation) <> "" Then
Application.FollowHyperlink Me.txtPdfLocation
End If
End Sub

vba - export Access table to file named by user

I'm currently exporting a table in Access 2013 to an Excel file using TransferSpreadsheet. I set the default filename and location. It's working fine, except that when the user changes the name they want to save the file as in the Save As dialog, the is not saved with that name. Is there a way I can get the file name the user entered in the Save As dialog and save the file with that name in the location they select?
Here's what I'm doing now:
Dim strTableName As String
Dim strBasePath As String
Dim strFullPath As String
Dim strFileName As String
Dim dlgSaveAs As Object
Const msoFileDialogSaveAs = 2
With CodeContextObject
strTableName = "New_Rules"
strBasePath = "C:\Users\" & Environ("USERNAME") & "\Documents\"
strFileName = "New_Account_Rules_" & Format(Date, "yyyy-mm-dd")
strFullPath = strBasePath & strFileName & ".xls"
' Display the Save As dialog with a default name and path
Set dlgSaveAs = Application.FileDialog(msoFileDialogSaveAs)
With dlgSaveAs
.InitialFileName = strFullPath
If dlgSaveAs.Show Then
' Do the export
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "New_Rules", strFullPath, True
End If
End With
Thanks in advance.
The SelectedItems() collection contains the list of filenames entered/selected. Since you're using the msoFileDialogSaveAs option, the FileDialog will permit only one selected item. So when .Show is True, just assign .SelectedItems(1) to your strFullPath variable:
With dlgSaveAs
' Set the initial/default filename...
.InitialFileName = strFullPath
If .Show Then
' Get the selected/entered filename...
strFullPath = .SelectedItems(1)
' Do the export...
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "New_Rules", strFullPath, True
End If
End With

Pointing MS Access to a variable path in VBA for exporting to Excel

I have a project I work on frequently, the data comes in Access & I need to export to Excel. The following code always worked until my company upgraded to Windows 2010 a couple of years ago. What happens is I'll point to the subdir I want (e.g. P:\project\evaluation\output) and it will save one subdir up (e.g. P:\project\evaluation).
The code:
Sub ExporttoXL()
Dim response, today
exportdir = fncOpenFolder()
today = Format(Date, "mmddyy")
response = InputBox("What is the date for the title of the output file? (Recommend: mmddyy format)", "Output file date for name", today)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
"Query001", "Output-" & response & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
"Query002", "Output-" & response & ".xls"
End Sub
----------------
Public Function fncOpenFolder() As String
Dim fdlg As Object
Set fdlg = Application.FileDialog(4) 'msoFileDialogFolderPicker
With fdlg
.AllowMultiSelect = False
.Title = "Select Folder"
If .Show = -1 Then
fncOpenFolder = .SelectedItems(1)
Else
fncOpenFolder = ""
End If
End With
Set fdlg = Nothing
End Function
The FileName argument to TransferSpreadsheet is supposed to be "the file name and path of the spreadsheet you want to import from, export to, or link to." But your code is giving it only the file name without the path. The exportdir variable is not used after you give it a value from fncOpenFolder().
Revise the code and use exportdir to include the path with the file name for the workbook which you want as the export target ...
Dim strFullPath As String
strFullPath = exportdir & "\Output-" & response & ".xls"
Debug.Print strFullPath '<- view this in Immediate window; Ctrl+g will take you there
'DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
' "Query001", "Output-" & response & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
"Query001", strFullPath

How to change MS query data source in excel with vba?

I have a couple tables that are connected to an access database through Microsoft Query. If I move the location of the access file or I need a way to update the source location especially since I will need to share this file with other people.
All the connections are ODBC and are from the same access file.
Since all the connection are uniform I looped through each one and replaced the current source file with the file selected through the windows file explorer.
Sub SwitchODBCSource()
Dim conn As WorkbookConnection
Dim sOldConnection As String, sNewConnection As String
getfilePath = Application.GetOpenFilename()
FileType = ".accdb"
If InStr(getfilePath, FileType) Then
fileName = Dir(getfilePath)
filePath = Replace(getfilePath, "\" & fileName, "")
For Each conn In ActiveWorkbook.Connections
With conn
conn.ODBCConnection.BackgroundQuery = False
conn.ODBCConnection.CommandType = xlCmdSql
conn.ODBCConnection.Connection = Array(Array( _
"ODBC;DSN=MS Access Database;DBQ=" & filePath & "\" & fileName & ";DefaultDir=" _
), Array( _
filePath & ";DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;" _
))
End With
Next conn
ActiveWorkbook.RefreshAll
Call Sheet1.dropDown
Set conn = Nothing
Else
MsgBox ("Can only use " & FileType & " files")
End If
End Sub

How to select the file whose name includes the newest date?

I am importing a CSV file into a table in MS Access.
However there are many files in the folder with the same extension and the names include dates in "mm_dd_yyyy" format.
Example: Lets say I have two CSV files:
my_music_02_10_2013_01_58_07_PM.csv
my_music_02_11_2013_03_04_07_PM.csv
Both files are in the same folder, myfolder. I want to import the file whose name contains the newest date.
Here is a short snippet of my code:
strPath = "F:\myfolder\"
strFile = Dir(strPath & "my_music" & "*.csv")
How can I determine which of my "my_music*.csv" is newest?
Seems to me the key is to extract the Date/Time from each file name so that you may compare those to find which of them is newest.
Here is an Immediate window session testing the function included below. The function returns null if it can't find a string which represents a valid date.
? DateFromFilename("my_music_02_10_2013_01_58_07_PM.csv")
2/10/2013 1:58:07 PM
? DateFromFilename("my_music_no_date_here.csv")
Null
Public Function DateFromFilename(ByVal pFileName As String) As Variant
Dim strBaseName As String
Dim strDate As String
Dim strPieces() As String
Dim varReturn As Variant
varReturn = Null
strBaseName = Split(pFileName, ".")(0)
'Debug.Print "strBaseName: " & strBaseName
strPieces = Split(strBaseName, "_")
If UBound(strPieces) = 8 Then
strDate = strPieces(4) & "-" & strPieces(2) & _
"-" & strPieces(3) & " " & strPieces(5) & ":" & _
strPieces(6) & ":" & strPieces(7) & " " & strPieces(8)
End If
'Debug.Print "strDate: " & strDate
If IsDate(strDate) Then
varReturn = CDate(strDate)
End If
DateFromFilename = varReturn
End Function