+ Reply to Thread
Results 1 to 15 of 15

Thread: Import Access Table contents with criteria.

  1. #1
    Valued Forum Contributor JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    Japan
    MS-Off Ver
    Excel 2010
    Posts
    779

    Import Access Table contents with criteria.

    I have been for weeks trying to get some code to import data from an Access Table between two specified dates into an excel file. I am trying to set an invoicing system that use Excel on the front end and Access on the back end to store the data.

    The table is simple enough with 5 columns, column 1 being the date the item was sold and the other 4 column showing the description of the product, how many items sold, the unit price and finally the total of the unit price and number sold.

    I am trying to import data at the the end of every month, which the criteria is always the previous two month data starting at the 16th of the month in question and ending two month later on the 15th.

    Eg. Today is Decmber 27th, so I need the data from October the 16th to December the 15th. Exactly 2 months worth of data. Next month will be November 16th to January 16th. etc, etc.

    I preferably want to do this via excel if I can.
    I have tried unsuccessfully to manipulate this code I got from the web.

    Sub ADOImportFromAccessTable(DBFullName As String, _
        TableName As String, TargetRange As Range)
    ' Example: ADOImportFromAccessTable "C:\FolderName\DataBaseName.mdb", _
        "TableName", Range("C1")
    Dim cn As ADODB.Connection, rs As ADODB.Recordset, intColIndex As Integer
        Set TargetRange = TargetRange.Cells(1, 1)
        ' open the database
        Set cn = New ADODB.Connection
        cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _
            DBFullName & ";"
        Set rs = New ADODB.Recordset
        With rs
            ' open the recordset
            .Open TableName, cn, adOpenStatic, adLockOptimistic, adCmdTable 
            ' all records
            '.Open "SELECT * FROM " & TableName & _
                " WHERE [FieldName] = 'MyCriteria'", cn, , , adCmdText 
            ' filter records
            
            RS2WS rs, TargetRange ' write data from the recordset to the worksheet
            
    '        ' optional approach for Excel 2000 or later (RS2WS is not necessary)
    '        For intColIndex = 0 To rs.Fields.Count - 1 ' the field names
    '            TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
    '        Next
    '        TargetRange.Offset(1, 0).CopyFromRecordset rs ' the recordset data
    
        End With
        rs.Close
        Set rs = Nothing
        cn.Close
        Set cn = Nothing
    End Sub
    Cheers

    Dave
    If you are happy with the answer, please click the Star icon in the below left hand corner.

    Good sites to start learning.

    snb's VBA Help Files
    Jerry Beaucaires Excel Assistant
    J & R Excel Consultancy Services

    How to post code correctly: Correct Code Posting

  2. #2
    Valued Forum Contributor JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    Japan
    MS-Off Ver
    Excel 2010
    Posts
    779

    Re: Import Access Table contents with criteria.

    I thought it would be a long shot. So can someone just point me to some code that will import one column no criteria and I can figure out the rest?
    If you are happy with the answer, please click the Star icon in the below left hand corner.

    Good sites to start learning.

    snb's VBA Help Files
    Jerry Beaucaires Excel Assistant
    J & R Excel Consultancy Services

    How to post code correctly: Correct Code Posting

  3. #3
    Forum Contributor
    Join Date
    12-26-2010
    Location
    Kansas City, Kansas
    MS-Off Ver
    Excel 2007
    Posts
    110

    Re: Import Access Table contents with criteria.

    Hi J

    The code below seems to work and was tested. You will have to change several
    items as indicated in the code.

    hth
    regards
    John

    Public Sub ImportFromAccess()
    
        ' * Save work book as Macro Workbook
        ' * Add General Module Alt-F11 - Insert Module
        ' * Tools -> References -> Microsoft ActiveX Data Objects 2.8
        ' * Tools -> References -> Microsoft ActiveX Data Recordset 2.8 Library
        ' * Tools -> References -> Microsoft ADO Ext 2.8 for DDL and Security
        ' * Paste this code into Module
    
        On Error GoTo EH_ImportFromAccess
    
        '------------------------------
        '   Objects
        '------------------------------
        Dim oCN As ADODB.Connection
        Dim oRS As ADODB.Recordset
        
        '------------------------------
        '   Properties
        '------------------------------
        Dim sProvider As String
        Dim sPath As String
        Dim sACCDBName As String
        Dim sWBName As String
        Dim sExtender As String
        Dim sDataSource As String
        Dim sCNString As String
        Dim sFullAccessFileName As String
        Dim sDoesFileExist As String
        Dim sTmp As String
        
        '------------------------------
        '   Counters
        '------------------------------
        Dim mlngRSRecCNT As Long
        Dim mlngRSFieldCNT As Long
        
        '------------------------------
        '   Misc
        '------------------------------
        Dim i As Integer
        Dim lng As Long
        
        '------------------------------
        '   SQL variables
        '------------------------------
        Dim sSQL As String
    
        '------------------------------
        '   WS Variables
        '------------------------------
        Dim sWS As String
        Dim oWS As Excel.Worksheet
        Dim oRng As Excel.Range
    
        '------------------------------
        '   Properties
        '------------------------------
        If Application.Version = 12# Then
            sProvider = "Microsoft.ACE.OLEDB.12.0;"
        Else
            sProvider = "Microsoft.Jet.OLEDB.4.0;"
        End If
        sPath = ThisWorkbook.Path & "\"         'Change to yours
        sACCDBName = "DBTarget.accdb"           'Change to yours
        sFullAccessFileName = sPath & sACCDBName
        sDoesFileExist = Dir(sFullAccessFileName)
        sExtender = vbNullString
        sDataSource = "Data Source = " & sPath & sACCDBName
        
        '------------------------------
        '   Does Access File Exist ?
        '------------------------------
        If Len(sDoesFileExist) < 2 Then
            sTmp = "The file named " & vbCrLf & vbCrLf
            sTmp = sTmp & sFullAccessFileName & vbCrLf & vbCrLf
            sTmp = sTmp & "does not exist ...................................... terminating"
            MsgBox sTmp, vbCritical, "Public Sub ImportFromAccess()"
            Exit Sub
        End If
    
        '------------------------------
        '   Connect To Access
        '------------------------------
        Set oCN = Nothing
        Set oCN = New ADODB.Connection
        With oCN
            .Provider = sProvider
            .ConnectionString = sDataSource
            .Open
        End With
    
        '------------------------------
        '   SQL Statement -
        '------------------------------
        '   Change to your Field Names
        '   Change to your Dates
        '   Change to your Table Name
        '------------------------------
        sSQL = "SELECT "
        sSQL = sSQL & " [Lastname], "
        sSQL = sSQL & " [Firstname], "
        sSQL = sSQL & " [MyRef], "
        sSQL = sSQL & " [MyDate] "
        sSQL = sSQL & " FROM "
        sSQL = sSQL & " [TargetTable] "
        sSQL = sSQL & " WHERE "
        sSQL = sSQL & " [MyDate] BETWEEN #12/27/2011# AND #2/27/2012#  "
        sSQL = sSQL & " ORDER BY "
        sSQL = sSQL & " [MyDate] "
    
        '------------------------------
        '   ADO Recordset
        '------------------------------
        Set oRS = Nothing
        Set oRS = New ADODB.Recordset
        With oRS
            .ActiveConnection = oCN
            .CursorLocation = adUseClient
            .CursorType = adOpenDynamic
            .LockType = adLockBatchOptimistic
            .Source = sSQL
            .Open
        End With
        
        '------------------------------
        '   Record Count and Field Count
        '------------------------------
        If Not oRS.BOF And Not oRS.EOF Then
            oRS.MoveLast
            oRS.MoveFirst
            mlngRSRecCNT = oRS.RecordCount
            mlngRSFieldCNT = oRS.Fields.Count
        Else
            '------------------------------
            '   No Records were returned
            '------------------------------
            sTmp = "The Recordset did not return any records " & vbCrLf & vbCrLf
            sTmp = sTmp & sSQL & vbCrLf & vbCrLf
            sTmp = sTmp & "Terminating ......"
            MsgBox sTmp, vbCritical, "Public Sub ImportFromAccess()"
            '--------------------------
            '   Kill Recordset Object
            '--------------------------
            On Error Resume Next
            If oRS.State <> 0 Then
                oRS.Close
                Set oRS = Nothing
            Else
                Set oRS = Nothing
            End If
            '--------------------------
            '   Kill Recordset Object
            '--------------------------
            If oCN.State <> 0 Then
                oCN.Close
                Set oCN = Nothing
            Else
                Set oCN = Nothing
            End If
            Exit Sub
        End If
    
        '--------------------------
        '   Write to a WS NAMED Target
        '--------------------------
        sWS = "Target"
        Set oWS = Sheets(sWS)
        With oWS
            .Activate
            .Cells.Delete
        End With
        
        '--------------------------
        '   Write FIELD Names
        '--------------------------
        For lng = 1 To mlngRSFieldCNT
            oWS.Rows(1).Columns(lng) = oRS.Fields(lng - 1).Name
        Next
        
        '--------------------------
        '   Write FIELD Names
        '--------------------------
        Set oRng = oWS.Range("a2")
        oRng.CopyFromRecordset oRS
        
        '--------------------------
        '   Kill Recordset Object
        '--------------------------
        On Error Resume Next
        If oRS.State <> 0 Then
            oRS.Close
            Set oRS = Nothing
        Else
            Set oRS = Nothing
        End If
    
        '--------------------------
        '   Kill Recordset Object
        '--------------------------
        If oCN.State <> 0 Then
            oCN.Close
            Set oCN = Nothing
        Else
            Set oCN = Nothing
        End If
    
    
        Exit Sub
    EH_ImportFromAccess:
        MsgBox Err.Number & " " & Err.Description, vbCritical, "Public Sub ImportFromAccess()"
        Exit Sub
    End Sub

  4. #4
    Valued Forum Contributor JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    Japan
    MS-Off Ver
    Excel 2010
    Posts
    779

    Re: Import Access Table contents with criteria.

    Hey John,

    Thanks for taking the time to reply. I do however keep getting an error saying it can't recognize the file. The error shows the DB path , but the path is correct, the file name also matches. So I am pretty much stumped right now.
    If you are happy with the answer, please click the Star icon in the below left hand corner.

    Good sites to start learning.

    snb's VBA Help Files
    Jerry Beaucaires Excel Assistant
    J & R Excel Consultancy Services

    How to post code correctly: Correct Code Posting

  5. #5
    Forum Contributor
    Join Date
    12-26-2010
    Location
    Kansas City, Kansas
    MS-Off Ver
    Excel 2007
    Posts
    110

    Re: Import Access Table contents with criteria.

    Hi J

    >>
    I do however keep getting an error saying it can't recognize the file.
    >>

    I put file checking in the code to test whether the files exists -
    does the error message say - in part - "File does not exist ..."

    This is the code that tests for the files existence - its part of the code I posted ..

    
        '------------------------------
        '   Does Access File Exist ?
        '------------------------------
        If Len(sDoesFileExist) < 2 Then
            sTmp = "The file named " & vbCrLf & vbCrLf
            sTmp = sTmp & sFullAccessFileName & vbCrLf & vbCrLf
            sTmp = sTmp & "does not exist ...................................... terminating"
            MsgBox sTmp, vbCritical, "Public Sub ImportFromAccess()"
            Exit Sub
        End If
    If that is the code that is firing off - then without a doubt - the directory + Filename
    does not exist.

    Can you post back precisely the directory and file name shown in the error message?

    regards
    John

  6. #6
    Valued Forum Contributor JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    Japan
    MS-Off Ver
    Excel 2010
    Posts
    779

    Re: Import Access Table contents with criteria.

    I get the error when it gets to the .open line in the below code.

    Set oCN = Nothing
        Set oCN = New ADODB.Connection
        With oCN
            .Provider = sProvider
            .ConnectionString = sDataSource
            .Open
        End With
    It jumps to the error handler.

    The message I get is , (Please remember I am translating this from Japanese, so it won't be the exact wording on an English ver of excel)
    -2147467259 Database Style
    Can't recognize 'C:\Users\Owner\Desktop\DBAccess.accdb'

    Cheers

    Dave
    If you are happy with the answer, please click the Star icon in the below left hand corner.

    Good sites to start learning.

    snb's VBA Help Files
    Jerry Beaucaires Excel Assistant
    J & R Excel Consultancy Services

    How to post code correctly: Correct Code Posting

  7. #7
    Forum Contributor
    Join Date
    12-26-2010
    Location
    Kansas City, Kansas
    MS-Off Ver
    Excel 2007
    Posts
    110

    Re: Import Access Table contents with criteria.

    Hi J

    Thank you very much for posting that.

    (a) We are past the Does Files exist thingie.

    (b) Either - it is burping on sProvider or sDataSource

    Can you put an F9 on the line .OPEN

    Then can your put sProvider and sDataSource in the debugger and confirm
    that they are as expected.

    As I posted - the code I posted works - but you have disproved this given your
    outcome.

    So - I want to propose TWO changes.

    First - can you confirm that you can manually open up the ACCESS database.
    Second - I want to modify the sDataSource Variable as follows:

    '------------------------------
    '------------------------------
    'Current
    sDataSource = "Data Source = " & sPath & sACCDBName

    'Add
    sDataSource = "Data Source = " & "'" & sPath & sACCDBName & "'"
    sDataSource = sDataSource & ";"

    I have tested the revision and it also works.

    regards
    John

  8. #8
    Forum Contributor
    Join Date
    12-26-2010
    Location
    Kansas City, Kansas
    MS-Off Ver
    Excel 2007
    Posts
    110

    Re: Import Access Table contents with criteria.

    Hi J

    I found the ADO error using google and it is here:
    http://support.microsoft.com/kb/209050

    -2147467259 (0x80004005) Unspecified Error

    This kind of error leaves us no place to go so I want to make a suggestion.

    (a) Manually create a NEW BLANK ACCESS database. You do NOT have to add any tables.

    (b) Modifiy the code I post to point to the new BLANK database.

    (c) Using F8 - walk down the code and see if it still crashes on the .OPEN line.

    regards
    John

  9. #9
    Valued Forum Contributor JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    Japan
    MS-Off Ver
    Excel 2010
    Posts
    779

    Re: Import Access Table contents with criteria.

    Hey John, thanks so much for your help so far.

    Unfortunately , even with those changes made in your last two post I am getting this same error. I have a sneaky feeling that the Japanese OS windows 7 may have something to do with this.
    If you are happy with the answer, please click the Star icon in the below left hand corner.

    Good sites to start learning.

    snb's VBA Help Files
    Jerry Beaucaires Excel Assistant
    J & R Excel Consultancy Services

    How to post code correctly: Correct Code Posting

  10. #10
    Forum Contributor
    Join Date
    12-26-2010
    Location
    Kansas City, Kansas
    MS-Off Ver
    Excel 2007
    Posts
    110

    Re: Import Access Table contents with criteria.

    Hi J

    Please see my previous post about creating a NEW BLANK database.

    If that fails - I am not certain whatelse to do.

    regards
    John

  11. #11
    Forum Contributor
    Join Date
    12-26-2010
    Location
    Kansas City, Kansas
    MS-Off Ver
    Excel 2007
    Posts
    110

    Re: Import Access Table contents with criteria.

    Hi J

    I bumped into these two thingies - BUT - I _ain't_ literate enough to read them.

    But please note:

    This is not an issue in Visual Studio .NET if you are using ADO.NET. But if you are using ADO, it is an issue. For .NET specific issues, see KnowledgeBase article 840667: You receive unexpected errors when using ADO and ADO Multidimensional in a .NET Framework application

    http://www.fmsinc.com/blog/post/Micr...ce-Pack-1.aspx

    http://support.microsoft.com/kb/2517589

    Perhaps one of the forum moderators have bumped up against this and so you might
    want to email one of them.

    Very sorry I could not help you.

    regards
    John

  12. #12
    Valued Forum Contributor JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    Japan
    MS-Off Ver
    Excel 2010
    Posts
    779

    Re: Import Access Table contents with criteria.

    Unfortunately, even after trying the blank DB I am still getting the same error. I am going to try a few different things and I will get back to this thread to report how I go. Thanks so much for help John.
    If you are happy with the answer, please click the Star icon in the below left hand corner.

    Good sites to start learning.

    snb's VBA Help Files
    Jerry Beaucaires Excel Assistant
    J & R Excel Consultancy Services

    How to post code correctly: Correct Code Posting

  13. #13
    Forum Contributor
    Join Date
    12-26-2010
    Location
    Kansas City, Kansas
    MS-Off Ver
    Excel 2007
    Posts
    110

    Re: Import Access Table contents with criteria.

    Hi J

    Please read the links on my last post. There maybe a service pack issue with OS7 that kills ***ADO***.

    I am not certain if it applies to your situation. I am _not_ certain if I am reading the link correctly,
    but I think so.

    regards
    John

  14. #14
    Valued Forum Contributor JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    Japan
    MS-Off Ver
    Excel 2010
    Posts
    779

    Re: Import Access Table contents with criteria.

    Hi John,

    OK, went through a whole heap of literature. It seems that the problem you speak of in your link is not what is happening to me. I can't understand it as I have another program using Access on the back end of excel. Of corse I did not do the code, but realized how useful using access on the back end of Excel can be, which is why I wanted to be able to make some code up myself. I am going to leave the thread unsolved for now and hopefully I will be able to come up with a solution and post it up.
    If you are happy with the answer, please click the Star icon in the below left hand corner.

    Good sites to start learning.

    snb's VBA Help Files
    Jerry Beaucaires Excel Assistant
    J & R Excel Consultancy Services

    How to post code correctly: Correct Code Posting

  15. #15
    Forum Contributor
    Join Date
    12-26-2010
    Location
    Kansas City, Kansas
    MS-Off Ver
    Excel 2007
    Posts
    110

    Re: Import Access Table contents with criteria.

    Hi J

    This is just as any FYI. Code below tested and works. Uses DAO in place of ADO.

    If u decide to give it a shot - DO NOT - reference DAO 3.6 in the references thingie - instead -
    reference

    ' * Tools -> References -> Microsoft Office 12.0 Access Database engine Object Library

    You can leave the current ADO references "as is".

    regards
    John


    Public Sub ImportFromAccess_DAO()
    
        ' * Save work book as Macro Workbook
        ' * Add General Module Alt-F11 - Insert Module
        ' * Tools -> References -> Microsoft ActiveX Data Objects 2.8
        ' * Tools -> References -> Microsoft ActiveX Data Recordset 2.8 Library
        ' * Tools -> References -> Microsoft ADO Ext 2.8 for DDL and Security
        
        '----------------------------
        '   NEW
        '----------------------------
        ' * Tools -> References -> Microsoft Office 12.0 Access Database engine Object Library
        
        '----------------------------
        '   DO **** NOT **** USE ----> DAO Ext 3.6
        '----------------------------
    
        '----------------------------
        '   DAO Objects
        '----------------------------
        Dim oDBEngine As DAO.DBEngine
        Dim oWorkSpace As DAO.Workspace
        Dim oDB As DAO.Database
        Dim oRS As DAO.Recordset
        Dim oQD As DAO.QueryDef
        Dim oCN As DAO.Connection
        
        '----------------------------
        '   Properties
        '----------------------------
        Dim sPath As String
        Dim sACCDBName As String
        Dim sWBName As String
        Dim sExtender As String
        Dim sDataSource As String
        Dim sCNString As String
        Dim sFullAccessFileName As String
        Dim sDoesFileExist As String
        Dim sTmp As String
        
        '------------------------------
        '   Counters
        '------------------------------
        Dim mlngRSRecCNT As Long
        Dim mlngRSFieldCNT As Long
        
        '------------------------------
        '   Misc
        '------------------------------
        Dim i As Integer
        Dim lng As Long
        
        '------------------------------
        '   SQL variables
        '------------------------------
        Dim sSQL As String
        
        '----------------------------
        '   Init
        '----------------------------
        sPath = ThisWorkbook.Path & "\"             'Change to yours
        sACCDBName = "DBTarget.accdb"               'Change to yours
        sFullAccessFileName = sPath & sACCDBName
        sDoesFileExist = Dir(sFullAccessFileName)
        
        '------------------------------
        '   Does Access File Exist ?
        '------------------------------
        If Len(sDoesFileExist) < 2 Then
            sTmp = "The file named " & vbCrLf & vbCrLf
            sTmp = sTmp & sFullAccessFileName & vbCrLf & vbCrLf
            sTmp = sTmp & "does not exist ...................................... terminating"
            MsgBox sTmp, vbCritical, "Public Sub ImportFromAccess()"
            Exit Sub
        End If
        
        '------------------------------
        '   SQL Statement -
        '------------------------------
        '   Change to your Field Names
        '   Change to your Dates
        '   Change to your Table Name
        '------------------------------
        sSQL = "SELECT "
        sSQL = sSQL & " [Lastname], "
        sSQL = sSQL & " [Firstname], "
        sSQL = sSQL & " [MyRef], "
        sSQL = sSQL & " [MyDate] "
        sSQL = sSQL & " FROM "
        sSQL = sSQL & " [TargetTable] "
        sSQL = sSQL & " WHERE "
        sSQL = sSQL & " [MyDate] BETWEEN #12/27/2011# AND #2/27/2012#  "
        sSQL = sSQL & " ORDER BY "
        sSQL = sSQL & " [MyDate] "
        
        '----------------------------
        '   Init
        '----------------------------
        Set oDBEngine = New DBEngine
        Set oWorkSpace = oDBEngine.Workspaces(0)
        Set oDB = oWorkSpace.OpenDatabase(sFullAccessFileName)
        Set oRS = oDB.OpenRecordset(sSQL)
        
        '----------------------------
        '   Ignore for now
        '----------------------------
        If 1 = 2 Then
            Set oQD = oDB.CreateQueryDef("", sSQL)
        End If
    
        '------------------------------
        '   Record Count and Field Count
        '------------------------------
        If Not oRS.BOF And Not oRS.EOF Then
            oRS.MoveLast
            oRS.MoveFirst
            mlngRSRecCNT = oRS.RecordCount
            mlngRSFieldCNT = oRS.Fields.Count
        Else
            '------------------------------
            '   No Records were returned
            '------------------------------
            sTmp = "The Recordset did not return any records " & vbCrLf & vbCrLf
            sTmp = sTmp & sSQL & vbCrLf & vbCrLf
            sTmp = sTmp & "Terminating ......"
            MsgBox sTmp, vbCritical, "Public Sub ImportFromAccess()"
            Exit Sub
        End If
    
        '--------------------------
        '   Write to a WS NAMED Target
        '--------------------------
        sWS = "Target"
        Set oWS = Sheets(sWS)
        With oWS
            .Activate
            .Cells.Delete
        End With
        
        '--------------------------
        '   Write FIELD Names
        '--------------------------
        For lng = 1 To mlngRSFieldCNT
            oWS.Rows(1).Columns(lng) = oRS.Fields(lng - 1).Name
        Next
    
        '--------------------------
        '   Write FIELD Names
        '--------------------------
        Set oRng = oWS.Range("a2")
        oRng.CopyFromRecordset oRS
    
    
    End Sub

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.2.0