Results 1 to 6 of 6
  1. #1
    vennies83 is offline Novice
    Windows XP Access 2007
    Join Date
    Jun 2011
    Posts
    5

    Excel Import Macro Help in Access

    I found a macro that was developed to automatically search a folder and import spreadsheets to a database, but it was formatted specifically for columns with numbers and such.



    My column setup is as follows:

    Code:
    Column Number	Column Name	Type
    1	Cost Center	Text
    2	Cost Eleme	Text
    3	Posting	Date
    4	CO Doc #	Text
    5	Amount	Text
    6	User Name	Text
    7	FI Doc	Text
    8	Vendor #	Text
    9	Name	Text
    10	Info Field	Text
    11	Doc Header Text	Text
    12	Line item Text	Text
    13	Invoice #	Text
    14	Entry dt	Date
    15	Inv date	Date
    16	Invoice Month	Date
    17	Housekeeping	Text
    I set up the code as follows, but it gives me an error in the INSERT INTO statement part, "Runtime Error 3075: Syntax Error (Missing Operator) in Query Expression 'Cost Eleme'. The error highlights at db.Execute sSQL.

    Thanks for your help!

    Code:
    Sub Import()
    Dim fs
    Dim fs2
    Dim SourceFolder
    Dim sSourceDir As String
    Dim CurrFile
    Rem the Excel Application
    Dim objExcel
    Rem the path to the excel file
    'Dim excelPath
    Rem how many worksheets are in the current excel file
    Dim worksheetCount
    Dim counter
    Rem the worksheet we are currently getting data from
    Dim currentWorkSheet
    Rem the number of columns in the current worksheet that have data in them
    Dim usedColumnsCount
    Rem the number of rows in the current worksheet that have data in them
    Dim usedRowsCount
    Dim row
    Dim column
    Rem the topmost row in the current worksheet that has data in it
    Dim top
    Rem the leftmost row in the current worksheet that has data in it
    Dim leftct
    Dim Cells
    Rem the current row and column of the current worksheet we are reading
    Dim curCol
    Dim curRow
    Rem the value of the current row and column of the current worksheet we are reading
    Dim word
    Dim sSQL As String
    Dim db As Database
    
    sSourceDir = "C:\Documents and Settings\R356112\Desktop\Housekeeping\2009"
    Set fs = CreateObject("scripting.filesystemobject")
    Set SourceFolder = fs.GetFolder("C:\Documents and Settings\R356112\Desktop\Housekeeping\2009")
    
    Set db = CurrentDb
    
    For Each CurrFile In SourceFolder.Files
        sFileName = CurrFile.Name
        sExcelFile = sSourceDir & "\" & sFileName
    
    If InStr(sFileName, ".xlsx") Then
    
    Debug.Print "Reading Data from " & sExcelFile
    
    Rem Create an invisible version of Excel
    Set objExcel = CreateObject("Excel.Application")
    
    Rem don't display any messages about documents needing to be converted
    Rem from  old Excel file formats
    objExcel.DisplayAlerts = 0
    Rem open the excel document as read-only
    Rem open (path, confirmconversions, readonly)
    objExcel.Workbooks.Open sExcelFile, False, True
    
    Rem How many worksheets are in this Excel documents
    worksheetCount = objExcel.Worksheets.Count
    
    Debug.Print "We have " & worksheetCount & " worksheets"
    
    Rem Loop through each worksheet
    For counter = 1 To worksheetCount
        Debug.Print "-----------------------------------------------"
        Debug.Print "Reading data from worksheet " & counter & vbCrLf
    
        Set currentWorkSheet = objExcel.ActiveWorkbook.Worksheets(counter)
        Rem how many columns are used in the current worksheet
        usedColumnsCount = currentWorkSheet.UsedRange.Columns.Count
        Rem how many rows are used in the current worksheet
        usedRowsCount = currentWorkSheet.UsedRange.Rows.Count
    
        Rem What is the topmost row in the spreadsheet that has data in it
        top = currentWorkSheet.UsedRange.row
        Rem What is the leftmost column in the spreadsheet that has data in it
        leftct = currentWorkSheet.UsedRange.column
    
        Set Cells = currentWorkSheet.Cells
        Rem Loop through each row in the worksheet
        For row = 0 To (usedRowsCount - 1)
        Rem Loop through each column in the worksheet
            curRow = row + top
            curCol = column + leftct
            If Cells(curRow, 1) <> "" Then
                sSQL = "INSERT INTO Imports (A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q) VALUES ("
                For column = 0 To usedColumnsCount - 1
                    Rem only look at rows that are in the "used" range
                    curRow = row + top
                    Rem only look at columns that are in the "used" range
                    curCol = column + leftct
                    Rem get the value/word that is in the cell
                    word = Cells(curRow, curCol).Value
                    Rem display the column on the screen
                    If curCol = 1 Then
                        sSQL = sSQL & "#" & word & "#,"
                    Else
                        sSQL = sSQL & word & ", "
                    End If
                    'Debug.Print "CurRow " & curRow & " CurCol " & curCol & " " & (word)
                Next
                                      
                sSQL = Left(sSQL, Len(sSQL) - 2) & ")"
                Debug.Print sSQL
                db.Execute sSQL
            End If
        Next
        Rem We are done with the current worksheet, release the memory
        Set currentWorkSheet = Nothing
    Next
    
    objExcel.Workbooks(1).Close
    objExcel.Quit
    End If
    Next
    
    Set currentWorkSheet = Nothing
    Rem We are done with the Excel object, release it from memory
    Set objExcel = Nothing
    db.Close
    
    End Sub

  2. #2
    ssanfu is offline Master of Nothing
    Windows 2K Access 2000
    Join Date
    Sep 2010
    Location
    Anchorage, Alaska, USA
    Posts
    9,664
    Do you really have field names in the table "Imports" that are "A,B,C,...Q"?? Since you have the column names in the Excel spreadsheet, I would have used the actual names as field names (without spaces or the special characters).

    You don't have the variable "sFileName", "sExcelFile" declared.
    Dim sExcelFile As String
    Dim sFileName As String

    Note: You should have these two lines at the top of every code page:
    Option Compare Database
    Option Explicit


    From looking at the code, it looks like you are missing the proper delimiters for the data types. Date fields require the delimiter '#" and text type fields require quotes (single or double).

    Would you post the SQL of the insert statement just before the db.Execute statement?

    Also, you might try using:

    db.Execute sSQL, dbFailOnError

    From HELP:
    In a Microsoft Jet workspace, if you provide a syntactically correct SQL statement and have the appropriate permissions, the Execute method won't fail — even if not a single row can be modified or deleted. Therefore, always use the dbFailOnError option when using the Execute method to run an update or delete query. This option generates a run-time error and rolls back all successful changes if any of the records affected are locked and can't be updated or deleted.

  3. #3
    vennies83 is offline Novice
    Windows XP Access 2007
    Join Date
    Jun 2011
    Posts
    5
    @ssanfu

    I made the updates you suggested, but got stuck on the date/text part you said.

    Do I need to populate the field headings in the Imports Table before I run the macro? All of the files I am looking for have the same headings and format.

    Thanks so much for your help. This will help me exponentially when it is all done.

    Here is the updated code:

    HTML Code:
    Option Compare Database
    Option Explicit
    Sub Import()
    Dim sExcelFile As String
    Dim sFileName As String
    Dim fs
    Dim fs2
    Dim SourceFolder
    Dim sSourceDir As String
    Dim CurrFile
    Rem the Excel Application
    Dim objExcel
    Rem the path to the excel file
    'Dim excelPath
    Rem how many worksheets are in the current excel file
    Dim worksheetCount
    Dim counter
    Rem the worksheet we are currently getting data from
    Dim currentWorkSheet
    Rem the number of columns in the current worksheet that have data in them
    Dim usedColumnsCount
    Rem the number of rows in the current worksheet that have data in them
    Dim usedRowsCount
    Dim row
    Dim column
    Rem the topmost row in the current worksheet that has data in it
    Dim top
    Rem the leftmost row in the current worksheet that has data in it
    Dim leftct
    Dim Cells
    Rem the current row and column of the current worksheet we are reading
    Dim curCol
    Dim curRow
    Rem the value of the current row and column of the current worksheet we are reading
    Dim word
    Dim sSQL As String
    Dim db As Database
    sSourceDir = "C:\Documents and Settings\R356112\Desktop\Housekeeping\2009"
    Set fs = CreateObject("scripting.filesystemobject")
    Set SourceFolder = fs.getfolder("C:\Documents and Settings\R356112\Desktop\Housekeeping\2009")
    Set db = CurrentDb
    For Each CurrFile In SourceFolder.files
        sFileName = CurrFile.Name
        sExcelFile = sSourceDir & "\" & sFileName
    If InStr(sFileName, ".xlsx") Then
    Debug.Print "Reading Data from " & sExcelFile
    Rem Create an invisible version of Excel
    Set objExcel = CreateObject("Excel.Application")
    Rem don't display any messages about documents needing to be converted
    Rem from  old Excel file formats
    objExcel.DisplayAlerts = 0
    Rem open the excel document as read-only
    Rem open (path, confirmconversions, readonly)
    objExcel.Workbooks.Open sExcelFile, False, True
    Rem How many worksheets are in this Excel documents
    worksheetCount = objExcel.worksheets.Count
    Debug.Print "We have " & worksheetCount & " worksheets"
    Rem Loop through each worksheet
    For counter = 1 To worksheetCount
        Debug.Print "-----------------------------------------------"
        Debug.Print "Reading data from worksheet " & counter & vbCrLf
        Set currentWorkSheet = objExcel.ActiveWorkbook.worksheets(counter)
        Rem how many columns are used in the current worksheet
        usedColumnsCount = currentWorkSheet.UsedRange.Columns.Count
        Rem how many rows are used in the current worksheet
        usedRowsCount = currentWorkSheet.UsedRange.Rows.Count
        Rem What is the topmost row in the spreadsheet that has data in it
        top = currentWorkSheet.UsedRange.row
        Rem What is the leftmost column in the spreadsheet that has data in it
        leftct = currentWorkSheet.UsedRange.column
        Set Cells = currentWorkSheet.Cells
        Rem Loop through each row in the worksheet
        For row = 0 To (usedRowsCount - 1)
        Rem Loop through each column in the worksheet
            curRow = row + top
            curCol = column + leftct
            If Cells(curRow, 1) <> "" Then
                sSQL = "INSERT INTO Imports (Cost Center,Cost Eleme,Posting,CO Doc #,Amount,User Name,FI Doc,Vendor #,Name,Info Field,Doc Header Text,Line item Text,Invoice #,Entry dt,Inv date,Invoice Month) VALUES("
                For column = 0 To usedColumnsCount - 1
                    Rem only look at rows that are in the "used" range
                    curRow = row + top
                    Rem only look at columns that are in the "used" range
                    curCol = column + leftct
                    Rem get the value/word that is in the cell
                    word = Cells(curRow, curCol).Value
                    Rem display the column on the screen
                    If curCol = 1 Then
                        sSQL = sSQL & "#" & word & "#,"
                    Else
                        sSQL = sSQL & word & ", "
                    End If
                    'Debug.Print "CurRow " & curRow & " CurCol " & curCol & " " & (word)
                Next
     
                sSQL = Left(sSQL, Len(sSQL) - 2) & ")"
                Debug.Print sSQL
                db.Execute sSQL, dbFailOnError
            End If
        Next
        Rem We are done with the current worksheet, release the memory
        Set currentWorkSheet = Nothing
    Next
    objExcel.Workbooks(1).Close
    objExcel.Quit
    End If
    Next
    Set currentWorkSheet = Nothing
    Rem We are done with the Excel object, release it from memory
    Set objExcel = Nothing
    db.Close
    End Sub
    Here is the SQL:

    HTML Code:
                sSQL = "INSERT INTO Imports (Cost Center,Cost Eleme,Posting,CO Doc #,Amount,User Name,FI Doc,Vendor #,Name,Info Field,Doc Header Text,Line item Text,Invoice #,Entry dt,Inv date,Invoice Month) VALUES("
                For column = 0 To usedColumnsCount - 1
                    Rem only look at rows that are in the "used" range
                    curRow = row + top
                    Rem only look at columns that are in the "used" range
                    curCol = column + leftct
                    Rem get the value/word that is in the cell
                    word = Cells(curRow, curCol).Value
                    Rem display the column on the screen
                    If curCol = 1 Then
                        sSQL = sSQL & "#" & word & "#,"
                    Else
                        sSQL = sSQL & word & ", "
                    End If
                    'Debug.Print "CurRow " & curRow & " CurCol " & curCol & " " & (word)
                Next
     
                sSQL = Left(sSQL, Len(sSQL) - 2) & ")"
                Debug.Print sSQL
                db.Execute sSQL, dbFailOnError

  4. #4
    ssanfu is offline Master of Nothing
    Windows 2K Access 2000
    Join Date
    Sep 2010
    Location
    Anchorage, Alaska, USA
    Posts
    9,664
    Code:
      sSQL = Left(sSQL, Len(sSQL) - 2) & ")"
      Debug.Print sSQL
      db.Execute sSQL, dbFailOnError
    When you run the code, the line in blue prints the insert statement in the debug window. Single step through the code and after the debug statement is executed, copy the SQL line from the debug window and post it.


    As to field names, you shouldn't use reserved words ("Name"), spaces or special characters (the shifted number keys) except dash (-) or underscore (_). Allen Browne has a list of reserved words here:
    http://allenbrowne.com/AppIssueBadWord.html

    Spaces and special characters cause headaches later on when designing queries, form and reports.

    Examples:
    Cost Center could be CostCenter, Cost_Center or Cost-Center
    CO Doc # could be CODocNum, CO_Doc_Num, or CO-Doc-Num

    "Name" is not very descriptive... Name of what??? DocName???

    "#" is the date delimiter.

    I prefer using "camel back" ....CostCenter

    OK, I'm off the soap box....

    still looking at the other code...

  5. #5
    ssanfu is offline Master of Nothing
    Windows 2K Access 2000
    Join Date
    Sep 2010
    Location
    Anchorage, Alaska, USA
    Posts
    9,664
    I modified a part of your code. The first modification is to the insert statement:

    Code:
        sSQL = "INSERT INTO Imports ([Cost Center],[Cost Eleme],Posting,[CO Doc #],Amount,[User Name],[FI Doc],[Vendor #],[Name],[Info Field],[Doc Header Text],[Line item Text],[Invoice #],[Entry dt],[Inv date],[Invoice Month]) VALUES("
    Then I modified the a section to add the correct delimiters:
    Code:
                         ' display the column on the screen
                         Select Case column + 1
                            Case 1, 2, 4 To 13, 17  'these fields are text type
                               sSQL = sSQL & "'" & ConvertQuotesSingle(word) & "', "
                               
                            Case 3, 14, 15, 16 ' these fields are date type
                               sSQL = sSQL & "#" & word & "#, "
                         End Select
    The function "ConvertQuotesSingle" ensures that if there is a single quote in the text, it is changed to two single quotes ('')
    Here is the "ConvertQuotesSingle" function code:
    Code:
    Function ConvertQuotesSingle(InputVal)
       ConvertQuotesSingle = Replace(InputVal, "'", "''")
    End Function
    If there is any chance that a cell in Excel could be NULL, you will have to add the NZ() function for the text fields:

    Code:
    sSQL = sSQL & "'" & ConvertQuotesSingle(NZ(word,"")) & "', "
    If a date field type could be NULL, you will have to decide if you will defaule the date to a specific date or modify the code to skip that field.

  6. #6
    vennies83 is offline Novice
    Windows XP Access 2007
    Join Date
    Jun 2011
    Posts
    5
    @ssanfu

    Thanks for all of your help!

    While searching around, I happened to find a way simpler import macro (at least I think so). The only thing is that in 2 instances out of 36 spreadsheets, the import error message came up, with only 3 errors out of roughly 200K lines that wouldn't be added, which is no biggie b/c they didn't matter anyway. The issue is the macro stops until you click ok, then it continues to import. Might you know a way to fix that to not happen?

    Please note that * is a substitute for the pathname, as it contained personal information.

    Code:
    Option Compare Database
    Option Explicit
    Function ImportExcel()
    Dim fs, fldr, fls, fl
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set fldr = fs.getfolder("C:\Documents and Settings\****\****\****")
    Set fls = fldr.Files
    For Each fl In fls
     
    If Right(fl.Name, 5) = ".xlsx" Then
    DoCmd.TransferSpreadsheet acImport, , "2011 SAP", "C:\Documents and Settings\****\****\****\" & fl.Name, True
    End If
     
    Next fl
    End Function

Please reply to this thread with any new information or opinions.

Similar Threads

  1. Import Excel File Using Macro?
    By oregoncrete in forum Import/Export Data
    Replies: 0
    Last Post: 04-05-2011, 12:26 PM
  2. Replies: 3
    Last Post: 12-21-2010, 11:52 AM
  3. Replies: 1
    Last Post: 10-15-2010, 06:09 AM
  4. Running excel macro from access
    By timpepu in forum Programming
    Replies: 1
    Last Post: 02-26-2010, 11:32 PM
  5. Macro To Import CSV to ACCESS
    By csvivek in forum Import/Export Data
    Replies: 1
    Last Post: 12-07-2009, 01:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Other Forums: Microsoft Office Forums