+ Reply to Thread
Results 1 to 29 of 29

Populating Cells With SQL Server Data

Hybrid View

  1. #1
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Populating Cells With SQL Server Data

    I need to run multiple queries and insert their results into Excel cells. Each query will return only one result (a number, or a null). What is the best way to accomplish this?

    Below is an example of the code I'm currently using. It does return data to the cell specified, but I'm guessing there's an easier way to populate multiple cells with the results of multiple queries.

    Sub GetData()
    Dim qt As QueryTable
    
    sqlstring = "SELECT DISTINCT(r.result_text)" & vbCrLf & _
    "FROM dt_sample s" & vbCrLf & _
    "LEFT OUTER JOIN dt_field_sample fs ON (s.facility_id = fs.facility_id and s.sample_id = fs.sample_id)" & vbCrLf & _
    "INNER JOIN dt_test t ON (s.sample_id = t.sample_id and s.facility_id = t.facility_id)" & vbCrLf & _
    "INNER JOIN dt_result r ON (t.test_id = r.test_id and t.facility_id = r.facility_id)" & vbCrLf & _
    "INNER JOIN rt_analyte a ON (r.cas_rn = a.cas_rn)" & vbCrLf & _
    "INNER JOIN dt_well d ON (s.sys_loc_code = d.sys_loc_code)" & vbCrLf & _
    "LEFT OUTER JOIN vw_locatiON l ON s.facility_id = l.facility_id and s.sys_loc_code = l.sys_loc_code" & vbCrLf & _
    "LEFT OUTER JOIN dt_task ts ON (s.task_code = ts.task_code and s.facility_id = ts.facility_id)" & vbCrLf & _
    "WHERE ((s.sample_date between '09/01/2008' and '12/31/2008') or s.sample_date is null)" & vbCrLf & _
    "AND r.result_text is not null" & vbCrLf & _
    "AND r.cas_rn = '79-01-6'" & vbCrLf & _
    "AND s.sys_loc_code = 'K2'"
    
    connstring = "ODBC;DSN=Fsn-db1\FSN_DB1;UID=;PWD=;Database=4040"
    
    Set qt = ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("H12"), Sql:=sqlstring)
    With qt
        .FieldNames = False
        .AdjustColumnWidth = False
        .PreserveFormatting = True
    End With
     
    qt.Refresh BackgroundQuery:=True
    
    End Sub
    Last edited by Salty Sea Dog; 07-29-2009 at 04:49 PM. Reason: Added Code

  2. #2
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Populating Cells With SQL Server Data

    Wow... this must be a lot more difficult than I thought...

  3. #3
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,136

    Re: Populating Cells With SQL Server Data

    Without knowing in what way the queries are different, or how (or if) they relate to any Excel data, it's impossible to answer really. It may be as easy as returning one recordset from your SQL server and then dropping the relevant records into particular cells, or you may be better off sticking with what you have.
    Everyone who confuses correlation and causation ends up dead.

  4. #4
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Populating Cells With SQL Server Data

    The query will be exactly the same with one exception: The criteria in the last line will change.

    For example, the first query looks for "AND s.sys_loc_code = 'K2'"
    The second will be "AND s.sys_loc_code = 'MW25'"
    The third "AND s.sys_loc_code = 'MW6'"

    Etc.

    When I try to just copy & paste the query and put the results in different cells, I get no data back at all. No errors or anything, just no data.

    Does that make a little more sense?

  5. #5
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Assign Value to Variable

    How do I assign the result of a query (SQL Server) to a variable? Pesudo:

    Dim varThis as string
    Set varThis = Query result
    Once the variable value is set, I would like to assign that value to a cell in Excel, in this case let's just say A1.
    Last edited by Salty Sea Dog; 07-30-2009 at 01:13 PM. Reason: A little more info

  6. #6
    Forum Guru DonkeyOte's Avatar
    Join Date
    10-22-2008
    Location
    Northumberland, UK
    MS-Off Ver
    O365
    Posts
    21,535

    Re: Assign Value to Variable

    Although only hypothetical code please add CODE tags around your pseudo-code in your first post.

    Set is only used with Objects (Workbook, Worksheet, Range etc...), Let for non-objects (strings, numeric types etc) which is implicit in VBA and thus does not need to be specified:

    Dim varThis As String
    varThis = Query Result
    Range("A1").Value = varThis
    Of course you could just assign the result to the cell directly

    Range("A1").Value = Query Result

  7. #7
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Assign Value to Variable

    Quote Originally Posted by DonkeyOte View Post
    Although only hypothetical code please add CODE tags around your pseudo-code in your first post.

    Set is only used with Objects (Workbook, Worksheet, Range etc...), Let for non-objects (strings, numeric types etc) which is implicit in VBA and thus does not need to be specified:

    Dim varThis As String
    varThis = Query Result
    Range("A1").Value = varThis
    Of course you could just assign the result to the cell directly

    Range("A1").Value = Query Result
    Ok, added CODE tags.

    What is the actual code to assign the query result? I have posted my entire code as it currently stands below.

    Sub GetData()
    Dim qt As QueryTable
    
    sqlstring = "SELECT DISTINCT(r.result_text)" & vbCrLf & _
    "FROM dt_sample s" & vbCrLf & _
    "LEFT OUTER JOIN dt_field_sample fs ON (s.facility_id = fs.facility_id and s.sample_id = fs.sample_id)" & vbCrLf & _
    "INNER JOIN dt_test t ON (s.sample_id = t.sample_id and s.facility_id = t.facility_id)" & vbCrLf & _
    "INNER JOIN dt_result r ON (t.test_id = r.test_id and t.facility_id = r.facility_id)" & vbCrLf & _
    "INNER JOIN rt_analyte a ON (r.cas_rn = a.cas_rn)" & vbCrLf & _
    "INNER JOIN dt_well d ON (s.sys_loc_code = d.sys_loc_code)" & vbCrLf & _
    "LEFT OUTER JOIN vw_locatiON l ON s.facility_id = l.facility_id and s.sys_loc_code = l.sys_loc_code" & vbCrLf & _
    "LEFT OUTER JOIN dt_task ts ON (s.task_code = ts.task_code and s.facility_id = ts.facility_id)" & vbCrLf & _
    "WHERE ((s.sample_date between '09/01/2008' and '12/31/2008') or s.sample_date is null)" & vbCrLf & _
    "AND r.result_text is not null" & vbCrLf & _
    "AND r.cas_rn = '79-01-6'" & vbCrLf & _
    "AND s.sys_loc_code = 'K2'"
    
    connstring = "ODBC;DSN=Fsn-db1\FSN_DB1;UID=;PWD=;Database=4040"
    
    Set qt = ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("H12"), Sql:=sqlstring)
    With qt
        .FieldNames = False
        .AdjustColumnWidth = False
        .PreserveFormatting = True
    End With
     
    qt.Refresh BackgroundQuery:=True
    
    End Sub

  8. #8
    Forum Guru DonkeyOte's Avatar
    Join Date
    10-22-2008
    Location
    Northumberland, UK
    MS-Off Ver
    O365
    Posts
    21,535

    Re: Assign Value to Variable

    I believe you've asked that question (albeit in a slightly different flavour) elsewhere...

    http://www.excelforum.com/excel-prog...rver-data.html

    FYI: the member assisting you on your other thread is one of the "real" gurus so you will be hard pushed to find superior advice / assistance from anyone else... I would suggest you persevere on the above thread.

  9. #9
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Assign Value to Variable

    Ok, however I'm trying to learn different ways of accomplishing the same task(s) as one may be more efficient than the other.

    I've stated that I'm not all that familiar with VBA. I'm just trying to explore my options. I also figured that asking in a different manner may bring more opinions and advice to the table. After all, if I can simply figure out how to assign the query result to a variable, I may very well be able to figure the rest out on my own.

    If having two posts that are simliar is a problem, feel free to delete this one.
    Last edited by Salty Sea Dog; 07-30-2009 at 01:26 PM.

  10. #10
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,136

    Re: Populating Cells With SQL Server Data

    Yep. I'd probably use one query with an IN clause containing all the codes rather than lots of separate ones.

  11. #11
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Populating Cells With SQL Server Data

    Quote Originally Posted by romperstomper View Post
    Yep. I'd probably use one query with an IN clause containing all the codes rather than lots of separate ones.
    That's what I was doing initially. But how can I use the IN clause and populate multiple cells? I'm guessing I can assign a range:

    Set qt = ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("H12:H20"), Sql:=sqlstring)
    But then the issue of spaces comes up. The cells I'm going to populate have various blank rows inserted for formatting purposes. How can I get around that?

    I was thinking something along the lines of assigning the query results to an array, and then populating individual cells with the values from that array. Would that work? If so, how would I do it? (I don't do a whole lot of VBA)

  12. #12
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Populating Cells With SQL Server Data

    romperstomper,

    That may be the way to go. I haven't tried getting the data back using an ADODB recordset.

    I will give this a shot.

    Thanks for your help!

  13. #13
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Populating Cells With SQL Server Data

    I'm getting an error saying "Login failed for user". Is there a way I can set up the connection to use the current Windows user credendials?

  14. #14
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Populating Cells With SQL Server Data

    Nevermind, got it.

  15. #15
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,136

    Re: Populating Cells With SQL Server Data

    Yep - replace the User ID bit with:
    Integrated Security=SSPI

  16. #16
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Populating Cells With SQL Server Data

    Ok, so this works. But I'm running into the same problem I ran into initially. I have roughly 40 or so queries I need to run. If I do the above 40 times and run each sub one-at-a-time I get my data back fine. However, if I attempt to run all of them, I only get data back for the last query (the last Sub in the editor). Is there a way around this?

  17. #17
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Populating Cells With SQL Server Data

    Ah, if I don't use a new Sub each time it looks like the results may be different. Trying now.

  18. #18
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,136

    Re: Populating Cells With SQL Server Data

    Yes, that's the plan - run it once to get back ALL of the data, then loop through the recordset putting each bit in the right cell.

  19. #19
    Registered User
    Join Date
    07-29-2009
    Location
    USA
    MS-Off Ver
    Excel 2003
    Posts
    31

    Re: Populating Cells With SQL Server Data

    This looks like it's going to do the trick. Thank you! I appreciate the help.

  20. #20
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,136

    Re: Populating Cells With SQL Server Data

    Glad to help!

  21. #21
    Registered User
    Join Date
    06-27-2012
    Location
    Perth, Australia
    MS-Off Ver
    Excel 2007
    Posts
    3

    Re: Populating Cells With SQL Server Data

    I know this is an old thread, but I just wanted to say thanks to Romper Stomper for a simple and elegant solution to the problem. I've been working on the same problem for about 10 hours and reading the code was like turning on a light - kudos!!

  22. #22
    Forum Expert JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    The grid, I got in!
    MS-Off Ver
    Excel 2010/13
    Posts
    1,696

    Re: Populating Cells With SQL Server Data

    Quote Originally Posted by gwunta View Post
    I know this is an old thread, but I just wanted to say thanks to Romper Stomper for a simple and elegant solution to the problem. I've been working on the same problem for about 10 hours and reading the code was like turning on a light - kudos!!
    Gwunta, I have to agree. I don't know how many times Romperstomper's code has helped me out, and helped me learn, which is why I always make a habit to subscribe to his threads ( Did not mean to talk about you Romper as if you were not here).
    Be fore warned, I regularly post drunk. So don't take offence (too much) to what I say.
    I am the real 'Napster'
    The Grid. A digital frontier. I tried to picture clusters of information as they moved through the computer. What did they look like? Ships? motorcycles? Were the circuits like freeways? I kept dreaming of a world I thought I'd never see. And then, one day...

    If you receive help please give thanks. Click the * in the bottom left hand corner.

    snb's VBA Help Files

  23. #23
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,136

    Re: Populating Cells With SQL Server Data

    You're welcome.

+ 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.6.0 RC 1