I need to find a way to import new data into a database which comprises of a SQL Server back end and an MS Access 2010 front end with linked tables to the back end, from the front end.
Ideally, this would involve a user clicking a button on a form in the front end and selecting an excel spreadsheet with new data to import, which would then be saved in the back end SQL Server tables.
I have created a vba module in the Excel spreadsheet I want to import. The code is:
Public Function ExcelPicker(Optional strFileName As String, _
Optional ByVal strWindowTitle As String = "Select an excel file") As String
Dim fd As Office.FileDialog
'Set fd = Application.FileDialog(msoFileDialogFolderPicker)
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Title = strWindowTitle
.Filters.Add "All files", "*.*", 1
.Filters.Add "Excel Workbooks", "*.xls;*.xlsx;*.xlsm", 2
.AllowMultiSelect = False
If .Show = -1 Then
FilePicker = (.SelectedItems(1))
Else
FilePicker = vbNullString
End If
End With
Set fd = Nothing
End Function
I have then created an import button on the MS Access 2010 front end, and in the OnClick event I have entered the code:
Private Sub cmdImportFilterResults_Click()
Dim sExcelFile As String
Set sExcelFile = Application.FileDialog(msoFileDialogFilePicker)
'' if sExcelFile is not blank then
'' import the file to MSSQL linked table
If sExcelFile <> "" Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "[Database].Table_Result", sExcelFile, True
End If
End Sub
However, when I click on the import button in the front end, nothing is happening. What is wrong in my code or my solution?
Here's a working example:
Private Sub cmdImportFilterResults_Click()
Dim strWindowTitle As String
Dim objDialog As Object
Dim sExcelFile As String
strWindowTitle = "Select an excel file"
Set objDialog = Application.FileDialog(msoFileDialogFilePicker)
With objDialog
.Title = strWindowTitle
.Filters.Add "Excel Workbooks", "*.xls;*.xlsx;*.xlsm", 1
.AllowMultiSelect = False
.Show
If .SelectedItems.Count = 0 Then
MsgBox "No File Selected."
Else
sExcelFile = Dir(.SelectedItems(1))
End If
End With
' if sExcelFile is not blank then
' import the file to MSSQL linked table
If sExcelFile <> "" Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "[Database].Table_Result", sExcelFile, True
End If
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.