在存储在Access中之前避免重复

时间:2018-02-14 20:56:09

标签: excel-vba ms-access vba excel

我有一个Excel文件,可以将新生成的数据存储到Access中(在保存事件之前),然后清理Excel。我想要做的是找出宏是否将存储基于第4列的副本,名为“Vendor_Parts”并跳过该项目的Access导出(已存在于Access中),然后继续导出。我有以下代码顺利运行:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

Dim DB As DAO.Database
Dim RS As DAO.Recordset
Dim erow As Integer

' open database
Set DB = DAO.OpenDatabase("my companies' database path")

' open table as a recordset
Set RS = DB.OpenRecordset("WDATA")

'set last empty row
erow = Sheets("Product Hierarchy").Cells(Rows.Count, 4).End(xlUp).Row

'iterate through each cell and fill values in Access

      With RS
      For erow = 2 To erow
            .AddNew
            !Date = Cells(erow, 1)
            !SKU_Rep = Cells(erow, 2)
            !Vendor_Parts = Cells(erow, 4)
            !PH = Cells(erow, 5)
            !GM = Cells(erow, 6)
            ' add more fields here
          .Update
       Next erow

    End With

'cleanup database
RS.Close

' close the database to avoid lockdown
DB.Close

Set RS = Nothing
Set DB = Nothing

'Clean information already sent to access
Range("A2:F1000000").ClearContents


End Sub

调用避免导出的重复检查程序的任何想法?谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用查询来检查重复项,并导入所有非重复数据。

This answer概述了构建查询以将Excel数据导入Access的一般方法。我们可以添加NOT EXISTS子句并检查是否存在重复

strSQL = "INSERT INTO WDATA([Date], SKU_Rep, Vendor_Parts, [other], [fields]) " & _
"SELECT F1, F2, F3, etc " & _
"FROM [Excel 12.0 Macro; HDR=No;Database=" & ActiveWorkbook.FullName & "].[Product Hierarchy$A2:G" & Sheets("Product Hierarchy").Cells(Rows.Count, 4).End(xlUp).Row & "]" & _
"WHERE NOT EXISTS (SELECT 1 FROM WDATA WHERE [Date] = F1 AND SKU_Rep = F2 And etc)"
db.Execute strSQL
db.Close