我想创建一个包含两个字段“ ID”和“ TempData”的临时表。然后想通过循环将数据从excel表插入到该表中。我创建了临时表,但是当我尝试向该表中添加数据时,它将失败。有谁有想法将excel列值移动到临时表而不循环? 谁能帮忙。
Sub MPNTEST()
Dim dbCon As ADODB.Connection, dbt As ADODB.Recordset, dbtf As ADODB.Field, r As Range, SqlQry1 As String
Set dbCon = New ADODB.Connection
Set dbt = New ADODB.Recordset
dbCon.ConnectionString = SqlConStr
On Error GoTo CloseConnection
SqlQry1 = "Use tempdb CREATE TABLE #TempTbl ( ID INT Primary KEY IDENTITY(1,1),TempData NVARCHAR(255))"
dbCon.Open
dbCon.Execute (SqlQry1)
With dbt
.ActiveConnection = dbCon
.Source = "#TempTbl"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
For Each r In ActiveSheet.Range("AE2:AE10")
.AddNew
.Fields("TempData").Value = r.Value
.Update '###Here it fails
Next r
End With
dbt.Close
dbCon.Close
End Sub
答案 0 :(得分:0)
希望获得帮助(我尚未测试:
Sub MPNTEST()
Dim dbCon As ADODB.Connection, dbt As ADODB.Recordset
Dim dbtf As ADODB.Field, r As Range, SqlQry1 As String
Dim SQLInsert$
Set dbCon = New ADODB.Connection
'Set dbt = New ADODB.Recordset
dbCon.ConnectionString = SqlConStr
On Error GoTo CloseConnection
''create table db..table
SqlQry1 = "CREATE TABLE tempdb..#TempTbl ( ID INT Primary KEY IDENTITY(1,1),TempData NVARCHAR(255))"
dbCon.Open
dbCon.Execute (SqlQry1)
dbCon.Execute "use tempdb" ' Move to tempdb
With dbt
For Each r In ActiveSheet.Range("AE2:AE10")
SQLInsert = "Insert into #TempTbl(TempData) values('" & Replace(""& r.Value, "'", "''") &"')"
dbCon.Execute (SQLInsert)
Next r
End With
'dbt.Close
dbCon.Close
End Sub