Pregunta

I am facing an issue where I need to calculate some data based on existing data, then insert that data and finally, return it to an Excel file using VBA.

I have successfully been able to create a stored procedure that returns a table of values after inserting:

[...]
INSERT INTO [ExcelRGA] (RM_prefix, RM_suffix, editing, createdBy, editedBy) values (@RM_prefix, @RM_suffix, 1, @user, @user);

DECLARE @tab table (RM varchar(20))

INSERT @tab SELECT (@RM_prefix +'-' + right('00' + @RM_suffix, 3)) as 'RM';

SELECT * FROM @tab  
END

and this works! However, I am unable to get the values it is returning using VBA

Set oRS = New ADODB.Recordset
Set cmd = New ADODB.Command
Dim objRec As Object
cmd.ActiveConnection = oCon
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "dbo.newRM"

cmd.Parameters.Refresh
cmd.Parameters("@user").Value = "john"

Set oRS = cmd.Execute()

but I try to do something like

while not oRS.eof
   ....
wend

get an error message stating that the recordset is closed and I cannot do my thing.

All I am trying to do is secure the information that I have computed (RM_prefix and RM_suffix), insert them into my table and return them to my Excel file.

If there is a way to do this without using a store procedure (such as a function) that would also be great!

Please keep in mind that this is a multi-user environment, so generating the values in Excel, sending them to the SQL server for an insert doesn't give a 100% guarantee regarding the uniqueness of said data.

Thank you all for your precious help and inputs!

Peter

¿Fue útil?

Solución 2

Actually, the issue was coming from the SQL Stored Procedure. I've added SET NOCOUNT ON; right before the INSERT INTO [ExcelRGA] (RM_prefix, RM_suffix, editing, createdBy, editedBy) values (@RM_prefix, @RM_suffix, 1, @user, @user);

And it has solved my problem! I can now browse the recordset in VBA.

Thank you all for your help and inputs!

Otros consejos

You need something like this -

Private Function GetIDENTITY() As Long

oRS.Open "SELECT @@identity AS NewID", oCon


If Not IsNull(oRS.Fields("NewID")) Then

    GetIDENTITY = oRS.Fields("NewID"): oRS.Close

Else

    MsgBox "Error: Identity value not returned.", vbCritical

    End

End If

End Function
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top