vba to import excel file into a table

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!!!
cataliniAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
shanesuebsahakarnConnect With a Mentor Commented:
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
 
Rey Obrero (Capricorn1)Commented:
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
 
Rey Obrero (Capricorn1)Commented:

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
Get 10% Off Your First Squarespace Website

Ready to showcase your work, publish content or promote your business online? With Squarespace’s award-winning templates and 24/7 customer service, getting started is simple. Head to Squarespace.com and use offer code ‘EXPERTS’ to get 10% off your first purchase.

 
shanesuebsahakarnCommented:
...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
 
cataliniAuthor Commented:
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
 
cataliniAuthor Commented:
i tryed to past the code to open through api (shanesuebsahakarn), but it did not work...
0
 
shanesuebsahakarnCommented:
When you say it didn't work, what error message do you get?
0
 
Rey Obrero (Capricorn1)Commented:


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

Is there any rule against this?
0
 
shanesuebsahakarnCommented:
0
 
Rey Obrero (Capricorn1)Commented:
that is just his opinion
0
 
shanesuebsahakarnCommented:
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
 
cataliniAuthor Commented:
could you explain me better how to do it? what should i copy and paste? thanks.
0
 
shanesuebsahakarnCommented:
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
 
cataliniAuthor Commented:
i receive an error on this line...

DoCmd.TransferSpreadsheet , acImport, "MyTable", strFile, False
0
 
shanesuebsahakarnCommented:
You have an extra , in there - remove the , before the acImport.
0
 
cataliniAuthor Commented:
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
 
shanesuebsahakarnCommented:
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
 
cataliniAuthor Commented:
but why do the empty fields appear?

thanks
0
 
shanesuebsahakarnCommented:
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
 
cataliniAuthor Commented:
great!

thanks again for your very nice answers!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.