2010-02-24 160 views
0

我有以下代碼:VBA Excel中錯誤

Sub Stats1() 
Workbooks("2006_2007_2008.xls").Sheets("Sheet1").Select 
Worksheets("Sheet1").Activate 

    Dim my_cell As String 
    my_cell = InputBox("Which cell?") 

    Dim objConn As ADODB.Connection 

    Dim rsData As ADODB.Recordset 

    Dim strSQL As String 
     Dim mycell As String 

    szconnect = "Provider=SQLOLEDB;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=*****;Data Source=*****" 

     'Create the Connection and Recordset objects. 
    Set objConn = New ADODB.Connection 
     Set rsData = New ADODB.Recordset 

    On Error GoTo errHandler 

    'Open the Connection and execute the stored procedure 

    objConn.Open szconnect 

    strSQL = "SELECT *fom mytable" 
    objConn.CommandTimeout = 0 

    Set rsData = objConn.Execute(strSQL) 

    For iCols = 0 To rsData.Fields.Count - 1 

    ActiveSheet.Range(my_cell).Select 
    ActiveSheet.Cells(ActiveCell.Row, ActiveCell.Column + iCols).Value = rsData.Fields (iCols).Name 
    ActiveSheet.Cells.Font.Name = "Arial" 
    ActiveSheet.Cells.Font.Size = 8 

    Next 

    ActiveSheet.Range(ActiveSheet.Cells(ActiveCell.Row, ActiveCell.Column),  ActiveSheet.Cells(ActiveCell.Row, ActiveCell.Column + rsData.Fields.Count)).Font.Bold = True 

    If Not rsData.EOF Then 

'Dump the contents of the recordset onto the worksheet 

On Error GoTo errHandler 

ActiveSheet.Cells(ActiveCell.Row, ActiveCell.Column).CopyFromRecordset rsData 


    If Not rsData.EOF Then 

    MsgBox "Data set too large for a worksheet!" 

    End If 

    rsData.Close 



    End If 

    Unload frmSQLQueryADO 

    Exit Sub 

    errHandler: 

    MsgBox Err.Description, vbCritical, "Error No: " & Err.Number 

'Unload frmSQLQueryADO 

    End Sub 

我得到的「424所需的對象錯誤」 ......不知道是什麼問題...! 我想我已經添加了所有正確的引用

+1

__VAB__在Excel中的錯誤。這是一個錯字嗎? – 2010-02-24 15:41:07

+0

哪一行發生錯誤? – 2010-02-24 15:42:51

+0

我不知道..因爲程序執行得很好,。,我得到的查詢結果,並在最後..我得到錯誤..如果我調試..我什麼都沒有得到.... – andreas 2010-02-25 05:50:36

回答

1

一個明顯的問題:

strSQL = "SELECT *fom mytable" 

應該

strSQL = "SELECT * from mytable" 

編輯:我測試了上面的代碼中的一個實物模型,雖然它應該大大整理,它確實有效。因此,我建議的錯誤是在這一行:

Unload frmSQLQueryADO 

嘗試註釋行,看它是否工作。

+0

nope..not it ... SQL執行正常..上面的SQL只是一個例子... – andreas 2010-02-25 05:49:58

+0

我已經添加了進一步的說明。 – Fionnuala 2010-02-25 11:29:36

0

rsData是從查詢返回的記錄集,而不是連接。

嘗試objConn.Close代替