Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 745
Randal Avatar asked Sep 13 '11 16:09

Randal


People also ask

Can I import an Excel spreadsheet into Microsoft Access?

You can bring the data from an Excel workbook into Access databases in many ways. You can copy data from an open worksheet and paste it into an Access datasheet, import a worksheet into a new or existing table, or link to a worksheet from an Access database.

How do I import data from Excel to Access database in VB net?

You import your data into a dataset(ds1) from Excel worksheet and create the other dataset(ds2) which is populated by the dataadapter from Access database. Then modify the data in ds2. Finally we can use DataAdapter. Update method to save the data change to database.

How do you get data from MS Access with Excel VBA code?

Answer: To access a value directly from a table using VBA code, you first need to create a new Module. To do this, open the Database window, select the Modules tab and click on the New button. When the Microsoft Visual Basic window appears, you can create a new function to retrieve the value from the table.


1 Answers

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!"
like image 95
HansUp Avatar answered Nov 01 '22 12:11

HansUp