Results 1 to 14 of 14
  1. #1
    RunTime91 is offline Competent Performer
    Windows 8 Access 2013
    Join Date
    Dec 2014
    Posts
    281

    Trying To Extract Data From Access Using Excel VBA

    Greetings All...

    Both code snippets are written in Excel VB Editor and are designed to simply extract data from Access and place it on a specific Excel sheet in a Specific Range

    The below code works perfectly when I hard code the date
    Code:
    Sub RefreshData3()Dim Db As DAO.Database
    Dim Rs As DAO.Recordset
    Dim xlBook As Workbook
    Dim xlSheet As Worksheet
    Dim RecCount As Long
    Dim SQL As String
    
    'Setup Reference To Workbook And Sheet
    Set xlBook = ActiveWorkbook
    Set xlSheet = xlBook.Worksheets("Sheet1")
    Application.ScreenUpdating = False
    xlSheet.Range("Q7:Z9").Clear
    'Communicate With User
    Application.StatusBar = "Connection to an External Database..."
    'Application.Cursor = xlWait
    Set Db = OpenDatabase(DbLoc)
            
    StrSQL = "SELECT vProductionDetails.Entered, Sum(IIf([CaseStatusDesc]= ""DMS"",1,0)) AS DMS, Sum(IIf([CaseStatusDesc]= ""EDI"",1,0)) AS EDI, " & _
                "Sum(IIf([CaseStatusDesc]= ""WARF"",1,0)) AS WARF, Sum(IIf([CaseStatusDesc]= ""Exceptions"",1,0)) AS EXC, " & _
                  "Sum(IIf([CaseStatusDesc]= ""R&R"",1,0)) AS [R&R] " & _
            "FROM vProductionDetails " & _
            "WHERE (((vProductionDetails.DB_ID) Not Like ""M*"") AND ((vProductionDetails.Special)=1)) " & _
            "GROUP BY vProductionDetails.Entered " & _
            "HAVING (((vProductionDetails.Entered) = ""12-19-2018"")) " & _
            "ORDER BY vProductionDetails.Entered DESC;"
    
    'Execute Query
    Set Rs = Db.OpenRecordset(StrSQL, dbOpenSnapshot)
    
    'Copy RecordSet to SpreadSheet
    Application.StatusBar = "Writing to SpreadSheet..."
    If Rs.RecordCount = 0 Then
      Msgbox "There Are No Records To Retrieve", vbInformation + vbOKOnly, "No Data"
      GoTo SubExit
      
    Else
      Rs.MoveLast
      RecCount = Rs.RecordCount
      Rs.MoveFirst
    End If
    xlSheet.Range("Q7:Z7").CopyFromRecordset Rs
    Once I had the above working I assigned the 'Date' to a variable using a date (same date - 12/19/2018) plugged in the one of the Excel sheets
    With the code below I get the "There Are No Records To Retrieve" error (which is an error 'cause there are records)
    Code:
    Sub RefreshData3()
    On Error GoTo SubError
    Dim Db As DAO.Database
    Dim Rs As DAO.Recordset
    Dim xlBook As Workbook
    Dim xlSheet As Worksheet
    Dim RecCount As Long
    Dim SQL As String
    
    Dim RunDate As Date
    RunDate = Sheets("DataEntry").Range("D4")
    
    'Setup Reference To Workbook And Sheet
    Set xlBook = ActiveWorkbook
    Set xlSheet = xlBook.Worksheets("Sheet1")
    Application.ScreenUpdating = False
    xlSheet.Range("Q7:Z9").Clear
    'Communicate With User
    Application.StatusBar = "Connection to an External Database..."
    'Application.Cursor = xlWait
    Set Db = OpenDatabase(DbLoc)
    
    StrSQL = "SELECT vProductionDetails.Entered, Sum(IIf([CaseStatusDesc]= ""DMS"",1,0)) AS DMS, Sum(IIf([CaseStatusDesc]= ""EDI"",1,0)) AS EDI, " & _
                "Sum(IIf([CaseStatusDesc]= ""WARF"",1,0)) AS WARF, Sum(IIf([CaseStatusDesc]= ""Exceptions"",1,0)) AS EXC, " & _
                  "Sum(IIf([CaseStatusDesc]= ""R&R"",1,0)) AS [R&R] " & _
            "FROM vProductionDetails " & _
            "WHERE (((vProductionDetails.DB_ID) Not Like ""M*"") AND ((vProductionDetails.Special)=1)) " & _
            "GROUP BY vProductionDetails.Entered " & _
            "HAVING ((vProductionDetails.Entered) = " & RunDate & ") " & _
            "ORDER BY vProductionDetails.Entered DESC;"
            
    Set Rs = Db.OpenRecordset(StrSQL, dbOpenSnapshot)
    
    'Copy RecordSet to SpreadSheet
    Application.StatusBar = "Writing to SpreadSheet..."
    If Rs.RecordCount = 0 Then
      Msgbox "There Are No Records To Retrieve", vbInformation + vbOKOnly, "No Data"
      GoTo SubExit
      
    Else
      Rs.MoveLast
      RecCount = Rs.RecordCount
      Rs.MoveFirst
    End If
    xlSheet.Range("Q7:Z7").CopyFromRecordset Rs
    I've tested the Date variable in the Immediate - It's correct
    I've surrounded the date in the SQL string with every character combination I can think of (single & double quotes, double-double quotes, hashtags, hashtags & quotes - you get the idea)
    Still all I can return is the No Records error...


    But clearly I'm missing something and that is what brings me here

    Help?

    Thanks so much...

  2. #2
    CJ_London is online now VIP
    Windows 10 Access 2010 32bit
    Join Date
    Mar 2015
    Posts
    11,445
    I presume the line you are having a problem with is this one


    Code:
    "HAVING ((vProductionDetails.Entered) = " & RunDate & ") " & _
    One of the problems with excel is it formats everything so you do not see the actual data. It also is fairly carefree with data types.

    So you need to ensure the datatype is correct and the value is correct.

    try

    "HAVING ((vProductionDetails.Entered) = #" & format(RunDate,"mm/dd/yyyy") & "#) " & _

    the format ensures the value is correct, the # ensures the datatype is correct

  3. #3
    Micron is offline Virtually Inert Person
    Windows 10 Access 2016
    Join Date
    Jun 2014
    Location
    Ontario, Canada
    Posts
    12,818
    you're saying you tried
    = #" & RunDate & "#) and it didn't work? Does the format of the sheet date value jive with your regional settings? Wondering about the dash as a date separator.
    The more we hear silence, the more we begin to think about our value in this universe.
    Paraphrase of Professor Brian Cox.

  4. #4
    CJ_London is online now VIP
    Windows 10 Access 2010 32bit
    Join Date
    Mar 2015
    Posts
    11,445
    Wondering about the dash as a date separator.
    I wondered about that, but the OP said this worked

    "HAVING (((vProductionDetails.Entered) = ""12-19-2018"")) " & _

    but then I wondered about the double double quotes, but if it works, it works - I would have expected a compile error

    Also I do know the format 'yyyy-mm-dd' works

  5. #5
    RunTime91 is offline Competent Performer
    Windows 8 Access 2013
    Join Date
    Dec 2014
    Posts
    281
    Ajax - Micron ~ Thank You so much for throwing down on this one

    I'm at a loss...

    I tried the following:

    #" & RunDate & "#
    #" & format(RunDate,"mm/dd/yyyy") & "#)
    #" & format(RunDate,"mm-dd-yyyy") & "#)
    #" & format(RunDate,"yyyy-mm-dd") & "#)

    Each attempt pulled the No Records Error

    Now, I did check the formats and sure enough the 'Entered' field in the Access table is formatted as Short Text - FTLOGod I have no idea why someone would do that
    And of course the Excel field is formatted as Date.

    So I changed the variable from Date to String and played around with single, double quotes and hashtags
    Had high hopes - but still the No Records Error

    Thoughts?

  6. #6
    June7's Avatar
    June7 is online now VIP
    Windows 10 Access 2010 32bit
    Join Date
    May 2011
    Location
    The Great Land
    Posts
    52,954
    Did you try:

    RunDate declared as string, use apostrophe delimiters (I prefer instead of doubled quote marks):

    Code:
    "HAVING vProductionDetails.Entered = '" & Format(RunDate, "12-19-2018") & "'" & _
    RunDate declared as a date value, convert the Access field value to true date:

    Code:
    "HAVING CDate(vProductionDetails.Entered) = #" & RunDate & "#" & _
    How to attach file: http://www.accessforums.net/showthread.php?t=70301 To provide db: copy, remove confidential data, run compact & repair, zip w/Windows Compression.

  7. #7
    RunTime91 is offline Competent Performer
    Windows 8 Access 2013
    Join Date
    Dec 2014
    Posts
    281
    Boom!

    This is simply the BEST Access Forum on the Net to get help with stuff like this

    After trying so many things I had become blind to things I hadn't tried and absent minded to the things I did try..

    If not for the three of you I would still be spinning my wheels

    Thank You, so very much Micron, Ajax & June!!

    Here is the solution that worked best. Of course, re-declaring RunDate as a String & the following
    Code:
    "HAVING (((vProductionDetails.Entered) = '" & Format(RunDate,"mm/dd/yyyy") & "'));"
    Since this data will be extracted for only a single date range - I removed the ORDER BY clause as well

    Again - Thank You to each of you...

    Now, on to the next...

  8. #8
    Micron is offline Virtually Inert Person
    Windows 10 Access 2016
    Join Date
    Jun 2014
    Location
    Ontario, Canada
    Posts
    12,818
    You're welcome and glad we could help, although in terms of that, should have put my name last?
    Other muses: I also would use ='" & someString & "' instead of "" as I find groups of double quotes can be temperamental; expecting """ & someStringI & """ would have been required in your case. As for the sql, I'm not seeing a need for Having as opposed to simply Where because you're not using any aggregate function on RunDate. You might find that making RunDate part of the Where clause runs faster if you've got a lot of records to search through.

  9. #9
    RunTime91 is offline Competent Performer
    Windows 8 Access 2013
    Join Date
    Dec 2014
    Posts
    281
    Hey Micron....
    After a simple review I agree on adding the Date criteria [Entered] to the WHERE... So I added it but it didn't work; I removed the GROUP BY and tried again - still nothing - Pull Entered from the SELECT statement - Not happening... The code below gives the least verbose error response which makes me think, once again, I'm close but can't quite get the punctuation correct...(and yes, I've moved the paren's around as well)
    Code:
    StrSQL = "SELECT vProductionDetails.Entered, Sum(IIf([CaseStatusDesc]= ""DMS"",1,0)) AS DMS, Sum(IIf([CaseStatusDesc]= ""EDI"",1,0)) AS EDI, " & _
                "Sum(IIf([CaseStatusDesc]= ""WARF"",1,0)) AS WARF, Sum(IIf([CaseStatusDesc]= ""Exceptions"",1,0)) AS EXC, " & _
                  "Sum(IIf([CaseStatusDesc]= ""R&R"",1,0)) AS [R&R] " & _
            "FROM vProductionDetails " & _
            "WHERE (((vProductionDetails.DB_ID) Not Like ""M*"") AND ((vProductionDetails.Special)=1) AND ((vProductionDetails.Entered) = '" & Format(RunDate, "mm/dd/yyyy") & "'));"
    As for your name being last? Nah, honestly, as helpful as this site has been for me everybody's name should be first, but it is kind of hard when thanking multiple folks -
    Anyway, since I completely agree with you on the WHERE placement of the RunDate I'm going to keep poking around with the above, meanwhile if you have a moment to take a look I would as always appreciate it.
    Thanks Micron...

    Edit: The Error I'm receiving is a 3122: Query does not include the specified expression 'Entered' as part of an aggregate function
    Last edited by RunTime91; 12-22-2018 at 09:25 AM. Reason: Add Error

  10. #10
    CJ_London is online now VIP
    Windows 10 Access 2010 32bit
    Join Date
    Mar 2015
    Posts
    11,445
    if you are summing, you need to group by the other fields you are selecting (i.e. not only in criteria)

  11. #11
    RunTime91 is offline Competent Performer
    Windows 8 Access 2013
    Join Date
    Dec 2014
    Posts
    281
    Ahhh, I completely understand - providing a little more info (the entire SQL Statement e.g.) always helps..

    Thanks Ajax...

  12. #12
    CJ_London is online now VIP
    Windows 10 Access 2010 32bit
    Join Date
    Mar 2015
    Posts
    11,445
    If you are not sure, use the query builder to get it how you want, then look at the sql view and adapt to run in VBA

  13. #13
    Micron is offline Virtually Inert Person
    Windows 10 Access 2016
    Join Date
    Jun 2014
    Location
    Ontario, Canada
    Posts
    12,818
    agree with the Group By comment, but am having second thoughts. You have enclosing single quotes ' around what looks like a date
    '" & Format(RunDate, "mm/dd/yyyy") & "'));"
    and the message seems to be pointing to that as being the problem. However, IIRC the format function converts a value to a string, in which case the quotes would make sense, but not if the field data type is Date/Time. You could try removing them and see what happens. Was just playing with that now, but I have the disadvantage of not having your db to test with. I also noticed that when I used Format(9/27/2017,"mm/dd/yyyy") Access insists on making it part of a HAVING clause. Note that that example is from the query sql view itself, which of course has to differ slightly from sql created in code with respect to quotes and such.

    If you want to provide a test db with some data and the query, I/we can see what can be made of it. On the other hand, if you've got it working in one fashion or another, then stick with what works.

  14. #14
    June7's Avatar
    June7 is online now VIP
    Windows 10 Access 2010 32bit
    Join Date
    May 2011
    Location
    The Great Land
    Posts
    52,954
    How to attach file: http://www.accessforums.net/showthread.php?t=70301 To provide db: copy, remove confidential data, run compact & repair, zip w/Windows Compression.

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

Similar Threads

  1. Replies: 0
    Last Post: 07-10-2018, 12:37 PM
  2. Replies: 4
    Last Post: 02-03-2017, 12:12 PM
  3. extract data from Access
    By sameerkadoo in forum Access
    Replies: 3
    Last Post: 06-06-2012, 12:15 PM
  4. Replies: 1
    Last Post: 02-02-2012, 08:55 AM
  5. Extract Specific Data from Access
    By iamstupid in forum Access
    Replies: 1
    Last Post: 05-26-2011, 12:58 AM

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