当我在excel vba中执行以下代码时,我遇到了获取所有列的问题。我只回到23列中的6个。
连接,命令等工作正常(我可以在SQL事件探查器中看到exec命令),为所有23列创建数据头但我只获得6列的数据。
方注意:它不是prod级代码,故意错过错误处理,sp在SQL管理工作室,ASP.Net,C#win form app中工作正常,它适用于Excel 2003连接到SQL 2008。
有人可以帮我解决问题吗?
Dim connection As ADODB.connection
Dim recordset As ADODB.recordset
Dim command As ADODB.command
Dim strProcName As String 'Stored Procedure name
Dim strConn As String ' connection string.
Dim selectedVal As String
'Set ADODB requirements
Set connection = New ADODB.connection
Set recordset = New ADODB.recordset
Set command = New ADODB.command
If Workbooks("Book2.xls").MultiUserEditing = True Then
MsgBox "You do not have Exclusive access to the workbook at this time." & _
vbNewLine & "Please have all other users close the workbook and then try again.", vbOKOnly + vbExclamation
Exit Sub
Else
On Error Resume Next
ActiveWorkbook.ExclusiveAccess
'On Error GoTo No_Bugs
End If
'set the active sheet
Set oSht = Workbooks("Book2.xls").Sheets(1)
'get the connection string, if empty just exit
strConn = ConnectionString()
If strConn = "" Then
Exit Sub
End If
' selected value, if <NOTHING> just exit
selectedVal = selectedValue()
If selectedVal = "<NOTHING>" Then
Exit Sub
End If
If Not oSht Is Nothing Then
'Open database connection
connection.ConnectionString = strConn
connection.Open
' set command stuff.
command.ActiveConnection = connection
command.CommandText = "GetAlbumByName"
command.CommandType = adCmdStoredProc
command.Parameters.Refresh
command.Parameters(1).Value = selectedVal
'Execute stored procedure and return to a recordset
Set recordset = command.Execute()
If recordset.BOF = False And recordset.EOF = False Then
Sheets("Sheet2").[A1].CopyFromRecordset recordset
' Create headers and copy data
With Sheets("Sheet2")
For Column = 0 To recordset.Fields.Count - 1
.Cells(1, Column + 1).Value = recordset.Fields(Column).Name
Next
.Range(.Cells(1, 1), .Cells(1, recordset.Fields.Count)).Font.Bold = True
.Cells(2, 1).CopyFromRecordset recordset
End With
Else
MsgBox "b4 BOF or after EOF.", vbOKOnly + vbExclamation
End If
'Close database connection and clean up
If CBool(recordset.State And adStateOpen) = True Then recordset.Close
Set recordset = Nothing
If CBool(connection.State And adStateOpen) = True Then connection.Close
Set connection = Nothing
Else
MsgBox "oSheet2 is Nothing.", vbOKOnly + vbExclamation
End If
答案 0 :(得分:0)
这一行:
Sheets("Sheet2").[A1].CopyFromRecordset recordset
正在复制With块之后的基础知识。 使用它或With块,但不能同时使用它们。
同样使用与类型名称不匹配的变量名称,只是要求难以找到问题。
除此之外,我会怀疑是存储过程,还是可能会抽取太多数据。