我将Excel表格中的数据导出到SQL Server数据库,如果存在UPDATE,则INSERT。
以下VBA代码适用于导出到ACCESS数据库, 但不是SQL SERVER DATABASE TABLE。
出现错误消息:.Index和.Seek的属性使用无效。
请帮助!!! TOH
Sub ExcelDataToSql ()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
Dim lastrow As Long, o As Long
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open "Provider=SQLNCLI11;Server=***;Database=****;Trusted_Connection=yes;"
rs.CursorLocation = adUseServer
rs.Open "InventorySQL", cn, 1, 3, adCmdTableDirect
' Get Lastrow
Worksheets("InventoryEXCEL").Select
lastrow = Worksheets("InventoryEXCEL").Cells(rows.Count, 1).End(xlUp).Row
r = 2 ' the start row in the worksheet
For o = 2 To lastrow
'Check For Duplicate In Database SQL
With rs
.Index = "PrimaryKey"
.Seek Range("A" & r).Value
If .EOF Then
.AddNew
'If No Duplicate insert New Record
rs.Fields("oPartno") = Range("A" & r).Value
rs.Fields("oDesc") = Range("B" & r).Value
rs.Fields("oCost") = Range("C" & r).Value
.update
Else
' If Duplicate Found Update Existing Record
rs.Fields("oDesc") = Range("B" & r).Value
rs.Fields("oCost") = Range("C & r).Value
.Update
End If
End With
Next o
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
MsgBox "Posting Completed"
End Sub
。 Index =" PrimaryKey" --- Sysntax错误:无效使用属性 。搜索范围(" A"& r).Value Sysntax错误:
答案 0 :(得分:1)
参考:Seek Method and Index Property Example (VB)
MSDN示例将Array作为第一个参数传递。
rstEmployees.Seek Array(strID), adSeekFirstEQ
第一个参数的名称os KeyValues
,它也暗示了一个数组
我会先尝试这个
。查看数组(范围(“A”& r).Value)
使用SeekEnum
值
更新: TOH OP发现这是相关代码段
MSDN还建议检查提供商是否支持.Index
和.Seek
If rstEmployees.Supports(adIndex) And rstEmployees.Supports(adSeek) Then
答案 1 :(得分:1)
我的问题通过解决来解决。
许多资源表明Sql Providers不支持索引和搜索功能。所以我避免索引和寻求
我通过将excel工作表作为源表导入到Sql server中来解决...之后将目标表与源表合并...如果匹配UPDATE,如果不匹配INSERT。
select * from InventoryTableSQL
select * from InventoryTableFromExcel
Merge InventoryTableSQL as T
using InventoryTableFromExcel as S
on t.oPartno = s.oPartno
when matched then
update set t.oPartno = s.oPartno,
t.oDesc = s.oDesc,
t.oCost = s.oCost
when not matched by target then
insert(oPartno, oDesc, oCost) values(s.oPartno, s.oDesc, s.oCost));