+3  A: 

I would guess that your stored procedure is returning more than one recordset.

If this is the case, you can use the NextRecordset() method to iterate through them.

MSDN:

  • If a row-returning command executes successfully but returns no records, the returned Recordset object will be open but empty. Test for this case by verifying that the BOF and EOF properties are both True.
  • If a non–row-returning command executes successfully, the returned Recordset object will be closed, which you can verify by testing the State property on the Recordset.
  • When there are no more results, recordset will be set to Nothing.

This means I would suggest something like this to solve your problem:

Set rs = cmd.Execute

''# fetch the first value of the last recordset
Do Until rs Is Nothing
  If rs.State = adStateOpen Then
    If Not (rs.BOF And rs.EOF) Then
      ''# You can do a different sanity check here, or none at all
      If rs.Fields(0).Type = adInteger Then
        CustomerId = rs.Fields(0).Value
      End If
    End If
  End If
  Set rs = rs.NextRecordSet
Loop

MsgBox CustomerId
Tomalak
This code seems to need a "rs.Open" call straight after the execute to get it to work? Is that right or am I missing something?
Stuart Helwig
When you execute a command, you get a recorset (or a bunch of them) back. They are open or closed, depending on whether they are result of a row-returning operation or not. If one of them is closed, it means that it was produced by an INSERT, for example. It does not mean that it must be opened. Your SELECT statement is a row-returning operation. It's attached recordset will be open, so I just check for "If rs.State = adStateOpen". All closed recordsets carry not much information other than that their statement was executed. They can be skipped in the loop.
Tomalak