Solved

Excel VBA query

Posted on 2011-09-20
11
168 Views
Last Modified: 2012-05-12
I am using the attached code to read a table from a MySQL database and would expect it to return all the table data into the worksheet, however it only returns the first column (primary key). Can anyone advise me please?

Excel 2007 & Mysql 5.5 with MySQL ODCB connector ver 5.1
Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 5.1 Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
& ";OPTION=3" 
    Set rs = New ADODB.Recordset
    sqlstr = "SELECT * FROM Clients;"
    rs.Open sqlstr, conn, adOpenOptimistic
    With Worksheets(3).Cells 
        .ClearContents
        .CopyFromRecordset rs
    End With

Open in new window

0
Comment
Question by:drwltd
  • 6
  • 5
11 Comments
 
LVL 33

Expert Comment

by:Norie
ID: 36566455
Is the worksheet completely empty with no hidden rows/columns?

Does the same happen when you try with a new worksheet?
Set wsNew = Worksheets.Add
Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 5.1 Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
& ";OPTION=3" 
    Set rs = New ADODB.Recordset
    sqlstr = "SELECT * FROM Clients;"
    rs.Open sqlstr, conn, adOpenOptimistic

   wsNew.Range("A1").CopyFromRecordSet rs

Open in new window

0
 

Author Comment

by:drwltd
ID: 36566537
Hi imnorie,

No hidden rows . columns and it does just the same on a new worksheet that I have created.
0
 
LVL 33

Expert Comment

by:Norie
ID: 36566557
Have you checked the query/table?

I tried this and it worked OK.
0
 

Author Comment

by:drwltd
ID: 36566574
I have run the query in mysql and it works fine. I get the same in Excel when querying 2 different tables
0
 
LVL 33

Expert Comment

by:Norie
ID: 36566616
You mean that when you query other tables you only get one field backed?

Try this which loops through the recordset to place the data.
Dim rng As Range


    Set conn = New ADODB.Connection
    conn.Open "DRIVER={MySQL ODBC 5.1 Driver}" _
              & ";SERVER=localhost" _
              & ";DATABASE=excel" _
              & ";UID=root" _
              & ";PWD=narflek" _
              & ";OPTION=3"
    Set rs = New ADODB.Recordset
    sqlstr = "SELECT * FROM invoices;"
    rs.Open sqlstr, conn, adOpenOptimistic


    Set rng = Worksheets(3).Range("A1")

    For I = 0 To rs.Fields.Count - 1

        rng.Offset(, I) = rs.Fields(I).Name
    Next I

    Set rng = rng.Offset(1)

    rs.MoveFirst

    While Not rs.EOF

        For I = 0 To rs.Fields.Count - 1
            rng.Offset(, I) = rs.Fields(I)
        Next I

        Set rng = rng.Offset(1)

        rs.MoveNext
    Wend
    
    rs.Close

    Set rs = Nothing

Open in new window

0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:drwltd
ID: 36566682
rs.fields.Count has a value of zero so again it only displays the first column (Primary key) but the query when run outside of Excel returns results as expected!
0
 
LVL 33

Expert Comment

by:Norie
ID: 36566747
I really don't understant that and I can't find any reference to it.

I did think it might be a driver thing but as far as I can see there haven't been any major changes since last year.

What happens when you go through Data>Get External Data...?
0
 

Author Comment

by:drwltd
ID: 36566788
I made an error and have run your test again, this time it returned the 28 field names and without the .name it returned the data values? That's a big step forward - I am going to do some more testing
0
 
LVL 33

Accepted Solution

by:
Norie earned 500 total points
ID: 36566829
In the first loop .Name is used to return the field name rather than the value.

In the second loop .Value should really be used, ie rs.Fields(i).Value.

0
 

Author Comment

by:drwltd
ID: 36566901
Yes I didn't realise that you had two loops only the first was visible in the window!
Using your code it works, I can see all the fields. Thanks for your help will award points
0
 
LVL 33

Expert Comment

by:Norie
ID: 36566917
I find the Select All button useful when copying code.:)
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Drop Down List with Unique/Distinct Values (enhancing the Combo-Box with a few steps and a little code) David miller (dlmille) Intro Have you ever created a data validation list from a database field or spreadsheet column (e.g., Zip Codes or Co…
Introduction While answering a recent question (http:/Q_27311462.html), I created an alternative function to the Excel Concatenate() function that you might find useful.  I tested several solutions and share the results in this article as well as t…
The viewer will learn how to simulate a series of coin tosses with the rand() function and learn how to make these “tosses” depend on a predetermined probability. Flipping Coins in Excel: Enter =RAND() into cell A2: Recalculate the random variable…
The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now