excel中的VBA错误

时间:2010-02-24 15:27:58

标签: vba

我有以下代码:

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对象必需错误”...不知道问题是什么......! 我想我已经添加了所有正确的参考文献

2 个答案:

答案 0 :(得分:1)

一个明显的问题:

strSQL = "SELECT *fom mytable"

应该是

strSQL = "SELECT * from mytable"
编辑:我在模拟中测试了上面的代码,虽然它应该被大大整理,但确实有效。因此,我建议错误在这一行:

Unload frmSQLQueryADO

尝试对该行进行评论并查看其是否有效。

答案 1 :(得分:0)

rsData是从查询返回的记录集,而不是连接。

尝试使用objConn.Close