vba - export Access table to file named by user - ms-access

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

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

Access VBA - Relink external excel workbook

How do I get MS Access to relink an external excel workbook via VBA macro?
I can do this using linked table manager but I would like to do this via VBA, so that I could create a button for users to press to locate the new workbook
Select new workbook
Relink external excel workbook
DoCmd.transferSpreadsheet aclink,,"Sales", "C:\Sales.xlsb", true, "Sales!E2:BC200"
I use the following code to reconnect to linked tables.
Public Function FixTableLink()
Dim db As Database
Dim strPath As String
Dim strConnect As String
strPath = CurrentProject.Path
strPath = strPath & "\DatabaseName.extention"
strConnect = ";DATABASE=" & strPath
Set db = CurrentDb
For Each tbl In db.TableDefs
If Nz(DLookup("Type", "MSysObjects", "Name = '" & tbl.name & "'"), 0) = 6 And tbl.Connect <> strConnect Then
tbl.Connect = strConnect
tbl.RefreshLink
End If
Next tbl
End Function
Change strPath to the path of your backend
You can use the following code to open a dialog box to search for the file path
Function SelectFile() As String
On Error GoTo ExitSelectFile
Dim objFileDialog As Object
Set objFileDialog = Application.FileDialog(1)
With objFileDialog
.AllowMultiSelect = False
.Show
Dim varSelectedItem As Variant
For Each varSelectedItem In .SelectedItems
SelectFile = varSelectedItem
Next varSelectedItem
End With
ExitSelectFile:
Set objFileDialog = Nothing
End Function
'File type filters can be added to the filedialog property using the following syntax:
'.Filters.Clear
'.Filters.Add "File Type Description", "*.file extension"
''Start folder can be specified using:
'.initialfilename="folder path"
Then in the first code block you can use
strPath =selectfile
Something like this, perhaps.
Dim InputFile As String
Dim InputPath As String
InputPath = "C:\ExcelPath\"
InputFile = Dir(InputPath & "*.xls")
Do While InputFile <> ""
DoCmd.TransferSpreadsheet acLink, , "Your table name","Path to your workbook file", True, "Sheet1!RangeYouNeed"
InputFile = Dir
Loop

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

Export Table to Excel and Open File

I want to export a table (the table is called "Consultations") to Excel, and open the file. I'm doing this from a form with a button. At this point, I have the file exporting correctly, but Excel is not staying open. I tried using xlApp.Visible = True, but it is only opening Excel while the file is exported, then it closes Excel when it is done.
What code will I need to insert in order to keep Excel (and the exported file) open?
Private Sub btnExportConsultations_Click()
Dim curPath As String
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
curPath = CurrentProject.Path & "\Consultations - " & Format(Date, "MM") & "-" & Format(Date, "dd") & "-" & Format(Date, "yyyy") & ".xlsx"
DoCmd.TransferSpreadsheet acExport, 10, "Consultations", curPath, -1
End Sub
Create the spreadsheet and then use Application.FollowHyperlink to open it in the application associated with that file type --- which should be Excel.
Private Sub btnExportConsultations_Click()
Dim curPath As String
curPath = CurrentProject.Path & "\Consultations - " & _
Format(Date, "mm-dd-yyyy") & ".xlsx"
DoCmd.TransferSpreadsheet acExport, 10, "Consultations", curPath, -1
Application.FollowHyperlink curPath
End Sub
Note I also changed the curPath = line. You can get your formatted date into the file name with a single Format() expression instead of three.
Open the workbook in the Excel object you created with the Excel application object's Workbooks.Open method. Also, I would export the file before messing with Excel - not sure if it makes a difference but I think the code flows better at the very least.
Private Sub btnExportConsultations_Click()
Dim curPath As String
Dim xlApp As Object
curPath = CurrentProject.Path & "\Consultations - " & Format(Date,"mm-dd-yyyy")
DoCmd.TransferSpreadsheet acExport, 10, "Consultations", curPath, -1
Set xlApp = CreateObject("Excel.Application")
xlApp.Workbooks.Open(curPath)
xlApp.Visible = True
End Sub

Import an Excel worksheet into Access using VBA

I am attempting to import an Excel spreadsheet into Access using some simple VBA code. The issue I have run into is there are 2 worksheets in the Excel file, and I need the 2nd worksheet to be imported. Is it possible to specify the needed worksheet in the VBA code?
Private Sub Command0_Click()
Dim dlg As FileDialog
Set dlg = Application.FileDialog(msoFileDialogFilePicker)
With dlg
.Title = "Select the Excel file to import"
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Excel Files", "*.xls", 1
.Filters.Add "All Files", "*.*", 2
If .Show = -1 Then
StrFileName = .SelectedItems(1)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8, "COR Daily", StrFileName, True
Else
Exit Sub
End If
End With
End Sub
Should I set StrFileName to 'StrFileName'&'.Worksheetname' ? Is that the proper naming scheme for that?
something like:
StrFileName = StrFileName & ".WorkSheetName"
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"