Import an Excel worksheet into Access using VBA - ms-access

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!"

Related

FileDialog not working in Access 2016

I am using FileDialog code for importing Excel table(s) into Access 2013-32 bit that works exactly like I want. When I use the code in Access 2016 I get an error in code that says "Can't find project of library". I have checked my references and they appear to be the same.
Here is my code:
Private Sub Command2_Click()
Dim JobName As String
Dim f As FileDialog
Dim tblImport As String
Dim varfile As Variant
Dim MyJobs As DAO.Recordset
JobName = lbl1.value
DoCmd.Close
Set f = Application.FileDialog(msoFileDialogFilePicker)
With f
.Title = "Choose Excel File(s) to Import"
.Filters.Clear
.Filters.Add "Excel Files", "*.xlsx"
.AllowMultiSelect = True
If f.Show = True Then
For Each varfile In .SelectedItems
Msgbox "IMPORTING: " & varfile
tblImport = varfile
DoCmd.TransferSpreadsheet acImport, 10, "Parts", tblImport, True
Next varfile
'Add Job Name to Parts Table
TempVars("jobName") = JobName
DoCmd.OpenQuery "Update Job Name"
'Add Job Name to Jobs Table
Set MyJobs = CurrentDb.OpenRecordset("Jobs")
MyJobs.AddNew
MyJobs![JobName] = JobName
MyJobs.Update
Set f = Nothing
Else
Msgbox "You Cancelled."
End If
End With
End Sub

Export query using file dialog from Access into one excel workbook using VBA and Macro

I have two queries. I would like these two queries added into one Excel (xlsx) file, but on two different Sheets, one for each query.
This is possible with a hardcoded path:
Public Function Export2Queries()
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SaneringsVurdering", "C:\Users\JGJ\Desktop\Sanering.xls", True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "K_SaneringLedMet", "C:\Users\JGJ\Desktop\Sanering.xls", True
End Function
Now I would like to combine this with a SaveAs dialog.
Option Compare Database
Public Function FilToSave()
Dim FlDia As FileDialog
Set FlDia = Application.FileDialog(msoFileDialogSaveAs)
With FlDia
.AllowMultiSelect = False
.InitialFileName = "C:\" ' You can set outfile to a full path with a fictitious or real file name, and the dialog will open in that folder.
.Title = "Please name the file you want to save"
If .Show = True Then
FilName = .SelectedItems(1)
Else
MsgBox "No file selected. Process cancelled"
DoCmd.Hourglass False
FilToSave = "Cancelled"
Exit Function
End If
End With
FilToSave = FilName
End Function
Got it to work with the above solution.
Public Function Export2Queries()
Dim savefile As String
savefile = FilToSave
If savefile <> "Cancelled" Then
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "SaneringsVurdering", savefile, True
End If
End Function
Now this code works for exporting a query/table to a wanted to location with dialog prompt.

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

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

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