Back in January, I promised to post a macro that imports data from Excel into Access programmatically.
(See My First Access Macro.)
It takes a given spreadsheet and imports it into a given Access file/table. The spreadsheet must have a header row, with no blank rows or columns inside the table block. You must set a reference to the appropriate Access object library (Microsoft Access x.0 Object Library).
How it works:
First it uses a simple API call to get the local username, so that the spreadsheet can be (temporarily) saved to the user's desktop. Then it checks to see if the .mdb file is already open by looking for a matching .ldb file — if an Access .mdb file is open, a .ldb file with the same name is created in the same folder to indicate that the database file is open/locked. We don't want to update a file that is already open by another user, to avoid data corruption.
The spreadsheet is saved to the user's desktop and closed for import. Then an instance of Access is started and the spreadsheet imported into the specified table. After a Msgbox is shown to confirm the import, the temp file is deleted from the desktop.
Option Explicit
' set a reference to Access Object Library before using this code
Public Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" ( _
ByVal lpBuffer As String, _
nSize As Long) As Long
' function to get username
Public Function Username() As String
Dim lpBuff As String * 1024
GetUserName lpBuff, Len(lpBuff)
Username = Left$(lpBuff, (InStr(1, lpBuff, vbNullChar)) - 1)
End Function
Sub ImportReportToAccess()
'
' open Access database and append ss to appropriate table
'
Application.ScreenUpdating = False
' first check if db file is locked, if so then don't run!
If Dir("C:\databasefile.ldb") = "" Then
' If a .mdb file is open, a matching .ldb file with the same name is opened in the same directory
Dim AWName As String
Dim UserN As String
' the newest report
AWName = ActiveWorkbook.Name
ActiveSheet.UsedRange
UserN = Username
Workbooks(AWName).SaveAs "C:\Documents And Settings\" & UserN & "\Desktop\" & AWName, FileFormat:=xlNormal
Workbooks(AWName).Close
Dim axsApp As Access.Application
Set axsApp = New Access.Application
With axsApp
.OpenCurrentDatabase "C:\databasefile.mdb", True
.DoCmd.OpenTable "table name"
.DoCmd.TransferSpreadsheet acImport, , "table name", "C:\Documents And Settings\" & UserN & "\Desktop\" & AWName, True
.CloseCurrentDatabase
End With
MsgBox "import complete"
Kill "C:\Documents And Settings\" & UserN & "\Desktop\" & AWName
Else
MsgBox ("Database file appears to be locked. Please try again later."), vbCritical
Exit Sub
End If
ExitProc:
Set axsApp = Nothing
Application.ScreenUpdating = True
End Sub
Enjoy,
JP
Great. What if the Excel file must be browsed? How do you use the dialog box in your code?
Hi JN,
Not sure what you mean. If you need to look at the file first, you can do that before you import to Access.
–JP
Hi JP,
When running your code access throws an error saying " sub or function not defined " refering to
Workbooks(AWName)…. I dont see this function defined anywhere in the code.
The code is meant to be used in Excel. Workbooks is a native object in Excel. It would need to be adapted for use in Access.
Hi,
I'm trying to update access with a certain data set from an excel file.. I just wanted to run the macro -not checking names/security.. so I used the below code:
Public Sub getdd() Dim axsApp As Access.Application Set axsApp = New Access.Application Dim path As String Dim pathXL As String pathXL = ...path of workbook path = ...path of database With axsApp .OpenCurrentDatabase path, True .DoCmd.OpenTable "Upload Type" .DoCmd.TransferSpreadsheet acImport, , "Upload Type", pathXL, True .CloseCurrentDatabase End With End Subthe table has two fields … "Upload ID" and "Upload Type"… I mimicked the data on the excel spreadsheet.. and the recordset was just a few rows of dummy data: 1 Upload A, 2 Upload B, 3 Upload C….and so on. I keep getting an error:
Field "F3" doesnt exst in destination table "upload type". Nothing in that field on my Excel though… any ideas?
Make sure the field names are exactly the same in the Access table and the Excel spreadsheet. You might also want to check for trailing spaces or unprintable characters. I also recommend you not use spaces in field names. And you might want to not use the same name for the table and the field, that could confuse Access. Try that and let me know if it works.
I am new to VBA. I am trying to import a .xls file into Microsoft Access 2007. The thought process is to import into existing fields in Access. I want it to ignore any additional fields the import file has. This will update the existing Access file in the database. Can you help me?
Randy,
Did you try the code in the post? The import file should have the same number of columns as the Access table, and the columns should be in the same order. Otherwise the results are unpredictable. Good luck and if you still can't get it to work, post the code you're using.
HTH
I'm trying to import data what will always be in the same directory as the DB, but never in the same directory over all. For example, Today it is in
"H:\March 25\Global Exco\data.xls"
Next week it will be in
"H:\April 2\Global Exco\data.xls"
Any idea how i can just import the data from the same directory that the DB is in?
If the spreadsheet and the database are always in the same folder, use ThisWorkbook.Path to get the current path (if the spreadsheet is open).
Thank you for taking time to help me out. What if the workbook isn't open? would i have to include code to open the workbook before executing the rest of the code?
Not necessarily. If the path always includes the date, you can build the string like this:
I have very similar code working in the background for a daily report that we run. This is weekly. And its hardly ever ran on the day in which we receive the data (i.e., get data weds. night and we run reports for the next week, until we get new set of data on the following weds) I first thought of using the CurrentDate code. Because the date changes weekly, I figured the best way is to keep the db and data files in the same directory. If you have any other suggestions, I would gladly try to implement them though. I really really do appreciate your help in this matter…
Just curious, (obviously I am a novice) – I am trying to take an existing MS DB and import data from Excel. The data in Excel was set up in fields. Not data-sheet view data. The fields for import are (ex: A5, B10, D15, C36 etc). Is there any way that I can load data such as this into Access when the fields that I want from Excel are all over the place like this?
You can do it, but not without VBA. Otherwise you'd need to organize your data as a table, i.e. with each field running across row 1 and the data below it. Then you can either import the spreadsheet (from Access) manually, or use VBA code in Access such as the DoCmd.TransferSpreadsheet method.