EXCEL VBA到SQL索引和寻求

我正在导出Excel表中的数据到SQL Server数据库,如果存在UPDATE else INSERT。

以下VBA代码适用于导出到ACCESS数据库,但不适用于SQL SERVER数据库表。

出现错误消息:.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 

。 索引=“PrimaryKey”— Sysntax错误:属性无效使用.Seek范围(“A”&r).Value Sysntax错误:

参考: 寻找方法和索引属性示例(VB)

MSDN示例传递一个数组作为第一个参数。

 rstEmployees.Seek Array(strID), adSeekFirstEQ 

第一个参数的名称是KeyValues ,它也暗示了一个数组

在这里输入图像说明

我会先试试这个

.Seek Array(Range(“A”&r).Value)

使用SeekEnum值之一也可能是有益的

在这里输入图像说明

更新: TO的OP发现这是relavent代码片段

MSDN也build议检查提供程序是否支持.Index.Seek

 If rstEmployees.Supports(adIndex) And rstEmployees.Supports(adSeek) Then 

我的问题通过解决办法解决。

许多资源表明,Sql Provider不支持索引和查找function。 所以我避免索引和寻求

我通过将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));