我正在尝试使用Teradata将表格从Excel导出到数据库中。我知道我有一个连接到DB,但是记录集没有打开,我收到错误3704“当对象关闭时不允许操作。这是我的代码。
Dim FullQry As String
Dim qry1 As String
Dim qry2 As String
Dim qry3 As String
Dim qry4 As String
Dim wb As Workbook, nWB As Workbook
Dim oWS As Worksheet, oExWS As Worksheet
Dim y As Long, z As Long
Dim aRange As Range, bRange As Range
Dim aData() As Variant
Application.StatusBar = "Pulling actuals data from TeraData"
DoEvents
Set wb = ThisWorkbook
Set oWS = wb.Sheets("LastRanSchedule")
' Set data range/array
With oWS
y = .Cells(2, 1).End(xlDown).Row
z = .Cells(1, 1).End(xlToRight).Column
Set aRange = .Range(.Cells(2, 1), .Cells(y, z))
aData = aRange
End With
'DECLARE VARIABLES FOR CONNECTION
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.ConnectionTimeout = 120
cn.CommandTimeout = 120
'DECLARE VARIABLES FOR RECORDSET
Dim RS As ADODB.Recordset
Set RS = New Recordset
'DECLARE VARIABLES FOR COMMAND
Dim cmdSQLData As ADODB.Command
Set cmdSQLData = New ADODB.Command
'Connect to Teradata
On Error GoTo errhndlr
cn.Open "Data Source = EDTDPAP1; Database= PROD_TECHOPS_LMP_SNBX_DB.AAL_Tableau_TestData; Persist Security info=True; User ID=" & UserID & "; Password=" & UserPassword & "; Session Mode=System Default;"
On Error GoTo 0
Set cmdSQLData.ActiveConnection = cn
RS.CursorType = adOpenKeyset
'RS.LockType = adLockOptimistic
RS.CursorLocation = adUseClient
'Export Data
Dim val As Variant
Debug.Print cn.State
Debug.Print RS.State
For i = 1 To y - 1
RS.AddNew
For j = 1 To z
val = aData(i, j)
If IsEmpty(val) Then
Else
RS.Fields(j) = val
End If
Next j
Next i
RS.UpdateBatch
单步执行代码,RS.AddNew
上会弹出错误。我的debug.print代码确认我的连接已打开但记录集已关闭。我已经没有想法,可以真正使用一些建议。感谢。
答案 0 :(得分:0)
所以我打开了记录集,虽然这创造了另一个问题,但如果需要,我会发布一个新问题。这是更新的代码。更改是通过RS连接。
'Connect to Teradata
On Error GoTo errhndlr
cn.Open "Data Source = EDTDPAP1; Database= PROD_TECHOPS_LMP_SNBX_DB.AAL_Tableau_TestData; Persist Security info=True; User ID=" & UserID & "; Password=" & UserPassword & "; Session Mode=System Default;"
On Error GoTo 0
'DECLARE VARIABLES FOR RECORDSET (THE RESULTS OF THE SQL QUERY)
Dim RS As ADODB.Recordset
Set RS = New Recordset
RS.CursorLocation = adUseClient
RS.CursorType = adOpenKeyset
RS.LockType = adLockOptimistic
RS.Open "SELECT * FROM PROD_TECHOPS_LMP_SNBX_DB.AAL_Tableau_TestData", cn
Set cmdSQLData.ActiveConnection = cn
答案 1 :(得分:0)
我这样用。
Dim Rs As ADODB.Recordset
Dim strConn As String
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.Path & dbName
Set Rs = New ADODB.Recordset
With Rs
.ActiveConnection = strConn
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.Source = "SELECT * FROM table "
.ActiveConnection = strConn
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.Open
For i = 1 To y - 1
For j = 1 To Z
Val = aData(i, j)
If IsEmpty(Val) Then
Else
.AddNew
.Fields(j) = Val
.Update
End If
Next j
Next i
.Close
End With
Set Rs = Nothing