我正在尝试从SQL存储过程返回的列标题,我已经调用了很好并且数据正在返回但是当我尝试访问列标题时它会失败,所以它会这样做。
Private Sub Refresh_Click()
Dim Conn As ADODB.Connection, RecordSet As ADODB.RecordSet
Dim Command As ADODB.Command
Dim ConnectionString As String, StoredProcName As String
Dim StartDate As ADODB.Parameter, EndDate As ADODB.Parameter
Application.ScreenUpdating = False
Set Conn = New ADODB.Connection
Set RecordSet = New ADODB.RecordSet
Set Command = New ADODB.Command
ConnectionString = "PROVIDER=SQLOLEDB;DATA SOURCE=DB;INITIAL CATALOG=DB; User Id=****;Password=****;"
On Error GoTo CloseConnection
Conn.Open ConnectionString
SellStartDate = Format(Sheets("Sheet1").Range("B2").Value2, "yyyy-mm-dd")
SellEndDate = Format(Sheets("Sheet1").Range("B3").Value2, "yyyy-mm-dd")
StoredProcName = "fsp_PLReportByDates"
With Command
.ActiveConnection = Conn
.CommandType = adCmdStoredProc
.CommandText = StoredProcName
End With
Set StartDate = Command.CreateParameter("@DateFrom", adDBDate, adParamInput, , SellStartDate)
Set EndDate = Command.CreateParameter("@DateTo", adDBDate, adParamInput, , SellEndDate)
Command.Parameters.Append StartDate
Command.Parameters.Append EndDate
Set RecordSet = Command.Execute
Sheets("Sheet1").Range("A7").CopyFromRecordset RecordSet
它在这里失败了,它试图得到列标题。我回来的全部是程序失败但是当我删除下面的代码来检索列标题时它会起作用。
我也想问一下,有没有办法自动为返回的数据添加过滤功能。
For i = 1 To RecordSet.Fields.Count
Worksheets("Sheet1").Cells(i, 1).Value = RecordSet.Fields(i).Name
Next i
如果我删除上面三行,它就会起作用并返回预期的数据而不是标题。
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
答案 0 :(得分:1)
字段为零
Network Admin > Settings > Network Settings
但是,将代码放在.copyfromrecordset之前 而不是之后。