Solved

Excel VBA SQL statement to get last ID

Posted on 2011-09-10
6
435 Views
Last Modified: 2012-05-12
Hi

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=196.220.43.237,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
        .Execute
    End With
    '------------------------------------------

Open in new window

0
Comment
Question by:murbro
[X]
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
6 Comments
 
LVL 4

Expert Comment

by:Friman001
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.
0
 
LVL 60

Expert Comment

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

Open in new window

0
 
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:
oLastID = "SELECT MAX(ID) AS ID FROM Table1"
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*
0
Comparison of Amazon Drive, Google Drive, OneDrive

What is Best for Backup: Amazon Drive, Google Drive or MS OneDrive? In this free whitepaper we look at their performance, pricing, and platform availability to help you decide which cloud drive is right for your situation. Download and read the results of our testing for free!

 
LVL 4

Accepted Solution

by:
AgeOfEmpires earned 500 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
  Else
    MsgBox "Error processing query"
  End If
  
  rs.Close
  con.Close
  Set rs = Nothing
  Set con = Nothing
  
End Sub

Open in new window

0
 

Author Closing Comment

by:murbro
ID: 36517304
Thanks very much
0
 
LVL 4

Expert Comment

by:AgeOfEmpires
ID: 36517450
Glad I could help
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
This Micro Tutorial demonstrates how to create Excel charts: column, area, line, bar, and scatter charts. Formatting tips are provided as well.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

705 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