Link to home
Start Free TrialLog in
Avatar of catalini
catalini

asked on

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!!!
Avatar of Rey Obrero (Capricorn1)
Rey Obrero (Capricorn1)
Flag of United States of America image

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
ASKER CERTIFIED SOLUTION
Avatar of shanesuebsahakarn
shanesuebsahakarn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

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

...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.
Avatar of catalini
catalini

ASKER

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


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

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

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

thanks
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.
great!

thanks again for your very nice answers!