0

我是 Excel VBA 的初学者。我想从 Teradata 数据库中查询数据并将输出提供到 Excel 工作表的行中。当我编写以下代码时:

Private Sub CommandButton1_Click()
    Dim conn As Connection
    Dim rec1 As Recordset
    Dim thisSql As String
    Set conn = New Connection
    conn.Open "Driver=Teradata; DBCName=" & DBCName & ";UID=" & UID & ";PWD=" & PWD
    thisSql = "simple select qyery here"
    With .QueryTables.Add(Connection:=conn, Destination:=.Range("A1"))
        .Sql = thisSql
        .Name = "data"
        .FieldNames = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

我收到错误消息“编译器错误:未定义用户定义的类型”

如何克服这个错误?我需要在代码中包含任何内容吗?

请帮忙

我正在使用 MSVisualBasic 6.5 编辑器

4

1 回答 1

4

嗨,我想在使用 QueryTables.Add 时它需要一个记录集作为连接对象。我修改了您的代码并尝试如下:

Dim conn As adodb.Connection
Dim rec1 As adodb.Recordset
Dim thisSql As String

Set conn = New adodb.Connection

conn.Open your_connection_string

thisSql = "your query here"

Set rec1 = New adodb.Recordset
rec1.Open thisSql, conn

With Sheet3.QueryTables.Add(Connection:=rec1, Destination:=Sheet3.Range("A1"))
    .Name = "data"
    .FieldNames = True
    .Refresh BackgroundQuery:=False
End With
于 2012-05-31T07:48:11.990 回答