[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now


Excel VBA SQL statement to get last ID

Posted on 2011-09-10
Medium Priority
Last Modified: 2012-05-12

In Excel VBA I am trying to get the last ID entered in a SQL table
How do I modify the following code to assign the
results of my SELECT statement to a string variable
called sMyLastID?
Dim oSQL As String
    On Error GoTo EH
    Set con = New ADODB.Connection
    con.Open "Provider=SQLOLEDB;Data Source=,1441;Network Library=DBMSSOCN;Initial Catalog=test;User ID=murbhhh;Password=chfff;"

    Set cmd = New ADODB.Command
    'Check last ID ---------------------------
    Dim oLastID As Variant
    oLastID = "SELECT MAX(ID) FROM Table1"
    With cmd
        .CommandText = oLastID
        .CommandType = adCmdText
        .ActiveConnection = con
    End With

Open in new window

Question by:Murray Brown
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Expert Comment

ID: 36516536
I could help easier if this was C#, but from what I see, you should just be able to say oLastId.ToString() and that should be holding the last ID.
LVL 60

Expert Comment

by:Kevin Cross
ID: 36516685
You want to assign it to variable during the execute.
intID = .ExecuteScalar()

Open in new window

LVL 60

Expert Comment

by:Kevin Cross
ID: 36516694
Sorry, it has been awhile since I messed with ADODB. You are using the Command object, so there is only Execute. Principle is the same, but looks more like this:
With cmd
    .CommandText = oLastID
    .CommandType = adCmdText
    .ActiveConnection = con
    Set rs = .Execute
End With

Open in new window

Where rs is an ADODB.Recordset, so you can get at the ID (note: I added an alias to your SQL string) like rs("ID"). You could use the column index since there will be only one. The index array starts at 1 if I am not mistaken so rs(1) but can always try rs(0). *smile*
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Accepted Solution

AgeOfEmpires earned 2000 total points
ID: 36517147
I typically use a command object if executing a stored procedure or a query that doesn't return info.  Otherwise I use a recordset to access the data.  I've not included any error checking for failed connection, incorrect query statements, etc.

Sub test()
  Dim sMyLastID As String
  Dim con As ADODB.Connection
  Dim rs As ADODB.Recordset
  Set con = New ADODB.Connection
  con.Open   ----your connection string here----
  Set rs = New ADODB.Recordset
  rs.Open "Select MAX(ID) From Table1", con, adOpenForwardOnly, adLockReadOnly
  If Not rs.EOF() Then
    sMyLastID = CStr(rs.Fields(0).Value)
    MsgBox "Max ID = " & sMyLastID
    MsgBox "Error processing query"
  End If
  Set rs = Nothing
  Set con = Nothing
End Sub

Open in new window


Author Closing Comment

by:Murray Brown
ID: 36517304
Thanks very much

Expert Comment

ID: 36517450
Glad I could help

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Some code to ensure data integrity when using macros within Excel. Also included code that helps secure your data within an Excel workbook.
In Part II of this series, I will discuss how to identify all open instances of Excel and enumerate the workbooks, spreadsheets, and named ranges within each of those instances.
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
This Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.

650 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