使用存储过程和命令时,VBA RecordSet.RecordCount = -1

时间:2017-12-10 00:18:12

标签: sql vba stored-procedures command recordset

我用命令调用存储过程。我在记录集中收到结果。现在我需要做一些计算,因此需要知道返回的记录数。 RecordSet.RecordCount应该给我但只返回-1。我尝试了不同的CursorType和CursorLocation值,尝试了MoveLast。什么都没有帮助。

我通过假设一个固定数量的记录来做出临时解决方案。

这里有很多关于RecordCount的帖子,还有我读过的文章,但似乎没什么帮助。我使用命令的问题是什么?我看到的大多数例子都不使用命令。

我是一名经验丰富的程序员,但不习惯SQL和VBA。谁可以给我一些帮助?

最诚挚的问候, 沃尔夫冈

Sub CallStoredProcedure()

Dim Conn As ADODB.Connection, RecordSet As ADODB.RecordSet

Dim Command As ADODB.Command
Dim ConnectionString As String, StoredProcName As String
Dim LoginID As ADODB.Parameter, Entity_Id As ADODB.Parameter

Application.ScreenUpdating = False

Set Conn = New ADODB.Connection
Set RecordSet = New ADODB.RecordSet
Set Command = New ADODB.Command

'w
RecordSet.CursorType = adOpenStatic
RecordSet.CursorLocation = adUseClient


ConnectionString = "Provider=SQLOLEDB;Data Source=HIQARBL218\SQLEXPRESS;Initial Catalog=SweSalaryStore;Trusted_Connection=yes;"

On Error GoTo CloseConnection

Conn.Open ConnectionString

StoredProcName = "dbo.getInfoFromSQLDB"

With Command
    .ActiveConnection = Conn
    .CommandType = adCmdStoredProc
    .CommandText = StoredProcName
End With

Set EMPNR = Command.CreateParameter("@EMPNR", adVarChar, adParamInput, 100, "107")
Command.Parameters.Append EMPNR

Set PERNR = Command.CreateParameter("@PERNR", adVarChar, adParamInput, 100, "1111110008")
Command.Parameters.Append PERNR

Set CMPNR = Command.CreateParameter("@CMPNR", adVarChar, adParamInput, 100, "5612")
Command.Parameters.Append CMPNR

Set PERIODFROM = Command.CreateParameter("@PERIODFROM", adVarChar, adParamInput, 100, "1001")
Command.Parameters.Append PERIODFROM

Set PERIODTO = Command.CreateParameter("@PERIODTO", adVarChar, adParamInput, 100, "1701")
Command.Parameters.Append PERIODTO

Set RecordSet = Command.Execute


Sheets("Sheet1").Range("A5").CopyFromRecordset RecordSet


'loop to get column headings.
For i = 0 To RecordSet.Fields.Count - 1
    Sheets("Sheet1").Cells(1, i + 1).Value = RecordSet.Fields(i).Name
Next i


'Calculate last row in RecordSet
Dim lastRow As Integer
lastRow = 2000
'lastRow = RecordSet.RecordCount 'NOT WORKING!!!

'Average OB
Dim AvgOB As Double
AvgOB = Excel.WorksheetFunction.Average(Range(Sheets("Sheet1").Cells(5, 2), Sheets("Sheet1").Cells(lastRow, 2)))
AvgOB = Excel.WorksheetFunction.Round(AvgOB, 2)
Sheets("Sheet1").Cells(2, 2).Value = AvgOB
Sheets("Sheet1").Cells(3, 2).Value = AvgOB * 12


RecordSet.Close
Conn.Close
On Error GoTo 0
Application.ScreenUpdating = True
Exit Sub

CloseConnection:
    Application.ScreenUpdating = True
    MsgBox "SQL Stored Procedure Did Not Execute Sucessfully!", vbCritical, "SQL Error"
    Conn.Close

End Sub

1 个答案:

答案 0 :(得分:0)

你已经完成了

 Sheets("Sheet1").Range("A5").CopyFromRecordset RecordSet  

所以此时返回的记录数是从a5向下占用的行数:

 Dim lastrow as long  'not integer!
 lastrow = Sheets("Sheet1").Range("A5").currentregion.rows.count + 4

加号四是从第5行开始