问题
I am a beginner in Excel VBA. I want to query data from Teradata database and give the output into the rows of an excel sheet. When i write the below code:
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
I am getting the error saying 'Compiler error: User-defined type not defined'
how to overcome this error? Do i need to include anything in the code?
Please help
I am using MSVisualBasic 6.5 editor
回答1:
Hi I guess it would need a recordset as the connection object when using QueryTables.Add. I modified your code and tried it as following:
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
来源:https://stackoverflow.com/questions/10828949/query-database-through-excel-vba