2010-02-07 255 views
0

我在執行excel vba中的以下代碼時遇到了取回所有列的問題。我只有23列中的6個回來。在Excel VBA中執行SQL SP

連接,命令等工作正常(我可以在SQL事件探查器中看到exec命令),爲所有23列創建數據頭,但我只獲得6列的數據。

側面說明:這不是督促級別的代碼,已經錯過了錯誤處理的目的,SP工作在SQL Management Studio中精細,ASP.Net,C#贏形式的應用程序,它爲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

recordset.Fields.Count返回什麼值? –

回答

0

這條線:

Sheets("Sheet2").[A1].CopyFromRecordset recordset 

被複制的基礎知識,後塊。 可以使用它或With塊,但不能同時使用。

也使用不匹配類型名稱的變量名稱,它只是要求很難發現問題。

除此之外,我會懷疑存儲過程,或者可能是太多的數據被拉。

+0

謝謝,我會把重複的行取出並修復其他位,sp在任何地方都能正常工作。它有大約11行23列的數據,是最小的一個。其他一些(尚未實施)將獲得數千行數據。 不知道接下來要嘗試什麼,但需要儘快完成。 – TheOCD