Solved

vba to import excel file into a table

Posted on 2004-08-28
20
52,605 Views
Last Modified: 2011-08-18
i need to create a button that imports an excel file as a table, asks for the location of the file to import, checks if the colum "Discount" is not null (and if null puts a zero as a value) and says "everything ok" if really everything ran ok... thanks!!!
0
Comment
Question by:catalini
  • 9
  • 7
  • 4
20 Comments
 
LVL 119

Expert Comment

by:Rey Obrero
ID: 11921963
you can use this codes to import the excel file
you need to add Microsoft Office xx Object Library to your refernces

Tools>References select the Microsoft Office xx Object Library          xx is the version number

Private Sub cmdGetExcelFile_Click()
Dim strFileName As String, strFileName1 as String, sTableName As String, strPath As String
Dim i As Integer
Dim fs As Object
Set fs = Application.FileSearch
With fs
    .LookIn = "C:\ExcelFiles"
    .fileName = "*.xls"
    If .Execute(SortBy:=msoSortbyFileName, _
    SortOrder:=msoSortOrderDescending) > 0 Then
        For i = 1 To .FoundFiles.Count
   

strPath = .FoundFiles(i)
strFileName = Dir(strPath)
strFileName1 = Left$([strFileName], InStr(1, [strFileName], ".") - 1)
sTableName = Mid(Replace(strFileName1, " ", ""), InStr(1, (Replace(strFileName1, " ", "")), "-") + 1)

         MsgBox "There were " & .FoundFiles.Count & _
            " file(s) found. And you want to Import " & strFileName
 
   
   DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
            "" & sTableName & "", strPath, True
   Next i
    Else
        MsgBox "There were no files found."
    End If
End With

End Sub
0
 
LVL 41

Accepted Solution

by:
shanesuebsahakarn earned 500 total points
ID: 11921985
Use the code here to bring up a file dialog:
http://www.mvps.org/access/api/api0001.htm

Paste it into a new module, and then you can get a file like so, let's say in a command button:

Private Sub cmdImport_Click()
Dim strFile As String
Dim strFilter As String

On Error Goto cmdImport_Error

strFilter=ahtAddFilterItem(strFilter,"Excel Files (*.xls)","*.xls")
strFile=ahtCommonFileOpenSave(Filter:=strFilter,OpenFile:=True,DialogTitle:="Select import file")
If strFile="" Then Exit Sub
DoCmd.TransferSpreadsheet acImport,,"MyTable",strFile,False
MsgBox "Everything ok!"
Exit Sub

cmdImport_Error:
MsgBox "Something went wrong! Error was: " & Err.Number & " " & Err.Description
End Sub

This line does the import:
DoCmd.TransferSpreadsheet acImport,,"MyTable",strFile,False

The last argument determines if the spreadsheet has field names (true) or not (false). You can specify the spreadsheet type in the second argument if you need to.
0
 
LVL 119

Expert Comment

by:Rey Obrero
ID: 11922076

another version
you need to add Microsoft Office xx Object Library to your references
 copy this to the form vba window

Option Compare Database
Option Explicit
Public fileName As String

Private Sub cmdGetFile_Click()
getFileName

Dim strFileName As String, sTableName As String
strFileName = Dir(fileName)
sTableName = Left$([strFileName], InStr(1, [strFileName], ".") - 1)
If fileName <> "" Then
   DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
            "" & sTableName & "", strFileName, True
    Else
    Exit Sub
End If

End Sub



Function getFileName()
    ' Displays the Office File Open dialog to choose a file name
  .
    Dim result As Integer
    With Application.FileDialog(msoFileDialogFilePicker)
        .Title = "Select Files"
        .Filters.Add "All Files", "*.*"
        .Filters.Add "Excel Files", "*.xls"
        .AllowMultiSelect = False
        .InitialFileName = CurrentProject.path
        result = .Show
        If (result <> 0) Then
            fileName = Trim(.SelectedItems.Item(1))
   
        End If
    End With
End Function

0
 
LVL 41

Expert Comment

by:shanesuebsahakarn
ID: 11922114
...why in the world would you declare the filename variable at module level?

One point to the original questioner. I neglected to read the second part of your question, about the Discount column. You'll need to run a query to update the Discount field after import - just put this line (modified for your table/field names) before the MsgBox line:
CurrentDb.Execute "UPDATE [MyTable] SET [Discount]=0 WHERE [Discount] Is Null"

If you need to do a lot of verification on your spreadsheet, I would import it into a table where all the fields are text and then append from that table to your real table. Importing from spreadsheets can be a little problematic at times because of how Access treats fields that contain only numeric characters (such as a phonenumber) - it will interpret these as numbers, not text.
0
 

Author Comment

by:catalini
ID: 11925277
is it possible to force access to adapt the excel file to the structure of the table already existing? thanks!
it should choose the first sheet of the excel file and do not take the empty lines... is it too difficult?

thanks again! :-)
0
 

Author Comment

by:catalini
ID: 11925379
i tryed to past the code to open through api (shanesuebsahakarn), but it did not work...
0
 
LVL 41

Expert Comment

by:shanesuebsahakarn
ID: 11925446
When you say it didn't work, what error message do you get?
0
 
LVL 119

Expert Comment

by:Rey Obrero
ID: 11926151


<...why in the world would you declare the filename variable at module level?>

Is there any rule against this?
0
 
LVL 41

Expert Comment

by:shanesuebsahakarn
ID: 11926166
0
 
LVL 119

Expert Comment

by:Rey Obrero
ID: 11926324
that is just his opinion
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 41

Expert Comment

by:shanesuebsahakarn
ID: 11926361
No, it isn't. It is considered bad programming style to use global variables for all of the reasons mentioned in that article. Do a google search, or post a question in some of the programming TAs, and you'll see what I mean.

There *ARE* uses for global variables, but if you don't have to use them, don't. There is no point in using a global variable just for the sake of it.
0
 

Author Comment

by:catalini
ID: 11932149
could you explain me better how to do it? what should i copy and paste? thanks.
0
 
LVL 41

Expert Comment

by:shanesuebsahakarn
ID: 11932278
Paste the code in the link that I gave you into a completely new module.

Then, you can paste the code that I posted into the OnClick event of your command button (ie this code):

Dim strFile As String
Dim strFilter As String

On Error Goto cmdImport_Error

strFilter=ahtAddFilterItem(strFilter,"Excel Files (*.xls)","*.xls")
strFile=ahtCommonFileOpenSave(Filter:=strFilter,OpenFile:=True,DialogTitle:="Select import file")
If strFile="" Then Exit Sub
DoCmd.TransferSpreadsheet acImport,,"MyTable",strFile,False
MsgBox "Everything ok!"
Exit Sub

cmdImport_Error:
MsgBox "Something went wrong! Error was: " & Err.Number & " " & Err.Description


You have to modify it slightly, but just change "MyTable" to the name of your own table.
0
 

Author Comment

by:catalini
ID: 11932366
i receive an error on this line...

DoCmd.TransferSpreadsheet , acImport, "MyTable", strFile, False
0
 
LVL 41

Expert Comment

by:shanesuebsahakarn
ID: 11932452
You have an extra , in there - remove the , before the acImport.
0
 

Author Comment

by:catalini
ID: 11932722
now it works... but after the import i receive a lot of empty record before my real records...

how can i specify which excel sheet to use? and the range of colums?
0
 
LVL 41

Expert Comment

by:shanesuebsahakarn
ID: 11932760
After the False option, you can specify the range of cells to import:
DoCmd.TransferSpreadsheet , acImport, "MyTable", strFile, "A1:D58"

for example. You can, however, just delete all the empty records after the import instead, for example:
CurrentDb.Execute "DELETE * FROM MyTable WHERE MyField Is Null"
0
 

Author Comment

by:catalini
ID: 11941937
but why do the empty fields appear?

thanks
0
 
LVL 41

Expert Comment

by:shanesuebsahakarn
ID: 11941962
This will be to do with the way your Excel file is formatted I imagine. Access often interprets empty cells as blank records if they appear above the real data, or if they once contained data that was deleted.
0
 

Author Comment

by:catalini
ID: 11942036
great!

thanks again for your very nice answers!
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

In the article entitled Working with Objects – Part 1 (http://www.experts-exchange.com/Microsoft/Development/MS_Access/A_4942-Working-with-Objects-Part-1.html), you learned the basics of working with objects, properties, methods, and events. In Work…
I see at least one EE question a week that pertains to using temporary tables in MS Access.  But surprisingly, I was unable to find a single article devoted solely to this topic. I don’t intend to describe all of the uses of temporary tables in t…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now