VBA Excel-SQL编码错误为"用户定义类型未定义" for" Recordset"

时间:2015-08-24 08:00:49

标签: sql-server vba sql-server-2008 excel-vba excel

我在VBA编码方面比较有经验,但我在MS SQL server 2008中是全新的。

我正在尝试将以下Excel表格导出到SQL服务器:

    A    B    C   D    E
1 Name  Year  ID 
2 Jill  2015  17
3 Jack  2012  13
4 Mike  1999  25
5

在工具中激活ADO和DAO后,它修复了错误"用户定义类型未定义"对于Dim rs As New ADODB.Recordset行。但现在我收到了Set dbclass = New clsDB行的错误。我不明白什么是错的。相同的定义结构适用于另一个工作簿。

Private Sub Transtable()

Dim connOk As Boolean
Dim MyWorkBook As Workbook
Dim CurSheet As Worksheet
Dim listObj As ListObject
Dim rs As New ADODB.Recordset
' Dim dbclass As New clsDB  ' both description leads to the same "User Undefined" error
' Dim dbclass As New ADODB.clsDB 
Set dbclass = New clsDB

dbclass.Database = "Tables"
dbclass.ConnectionType = SqlServer
dbclass.DataSource = "E72b1783"
dbclass.UserId = Application.UserName

  connOk = dbclass.OpenConnection(False, True)

  If connOk = False Then
     MsgBox "Connection not successfull"

  Else
     MsgBox "Connection successfull"
  End If

  tableName = "TableName1"
  Set CurSheet = Sheet2
  Set listObj = CurSheet.ListObjects(tableName) 'Table Name

  'get range of Table
  HeaderRange = listObj.HeaderRowRange.Address
  DataRange = listObj.DataBodyRange.Address

  dbclass.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=" & ThisWorkbook.FullName & ";" & _
    "Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

   strSQL = "SELECT * FROM [" & ws.Name & "$" & Replace(DataRange, "$", "") & "];"
   rs.Open strSQL, dbclass, adOpenStatic, adLockReadOnly

   arrData = rs.GetRows

   rs.Close
   dbclass.Close
   Set rs = Nothing
   Set dbclass = Nothing
   Set listObj = Nothing
   Set CurSheet = Nothing

End Sub

1 个答案:

答案 0 :(得分:1)

确保在工具中选中了数据访问对象库(DAO)。另请查看列表中的ActiveX数据对象库( ADO )。 VBA编辑器菜单/功能区中的引用列表。 (在不同版本的Access中,库的具体名称可能不同)