将源工作表中的唯一数据添加到主工作表

如果唯一的ID号码(SLW1 = MLW3),源列表工作表( SLW )列(1,2和3)中的一行需要粘贴到主列表工作表( MLW )列(3,4和5) 不在 “主列表”(同一工作簿)中已经存在。 我的第一个Excel VBA项目。 所以,任何build议/build议/更正/捷径都会很好。 这个代码是我摸索创造的。 如你所知,它不工作。

Sub Transfer() Dim SLR As Integer 'SourceList's Woksheets Last Row Dim MLR As Integer 'MasterList's Woksheets Last Row Dim SC As Integer 'SourceList Counting through the loop (ROW NUMBER) Dim SR As Range 'SourceList AC Row data '(Source information 3 rows to be transfered) Dim ID As Integer 'Unique code of Projects Dim Found As Range Sheets("SourceList").Activate SLR = Cells(Rows.Count, "A").End(xlUp).Row 'Start loop to go through SourceList unique ID numbers For SC = 2 To SLR 'Copy SourceList ID number into Variable "ID" ID = Sheets("SourceList").Range(1, SC) 'Also, Save Range into Variable so it doesn't have to 'go back and forth between Worksheets Set SR = Range(Cells(1, SC), Cells(3, SC)) Sheets("MasterList").Activate Found = Columns("C:C").Find(What:=ID, After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Activate If Found Is Nothing Then MLR = Cells(Rows.Count, "C").End(xlUp).Row + 1 Range(Cells(3, MLR)) = SR SR.ClearContents End If Sheets("SourceList").Activate Next SC End Sub 

虽然我已经发布了一个链接供您检查,但我会发布以前使用过的解决scheme。

 Sub ject() Dim con As Object: Set con = CreateObject("ADODB.Connection") Dim rec As Object: Set rec = CreateObject("ADODB.Recordset") Dim datasource As String datasource = ThisWorkbook.FullName ' returns the fullpath Dim sconnect As String sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _ "Data Source=" & datasource & ";" & _ "Extended Properties=""Excel 12.0;HDR=YES"";" con.Open sconnect Dim sqlstr As String ' This basically executes anti-join if you know SQL sqlstr = "SELECT * " sqlstr = sqlstr & "FROM [SWL$] e " sqlstr = sqlstr & "LEFT JOIN [MWL$] u " sqlstr = sqlstr & "ON e.ID = u.ID " sqlstr = sqlstr & "WHERE u.ID IS NULL " sqlstr = sqlstr & "AND e.ID IS NOT NULL;" rec.Open sqlstr, con, 3, 1 ' Dump data that meets your requirement With Sheets("MWL") Dim lr As Long lr = .Range("D" & .Rows.Count).End(xlUp).Row + 1 .Range("D" & lr).CopyFromRecordset rec End With End Sub 

注意事项:

  1. 您的SWLMWL表数据应从第1行开始,并带有标题。 在这里输入图像说明
  2. 两者都应该有包含唯一标识符的标题名称标识。 如果没有,你可以调整上面的代码。

所以,代码所做的就是访问ADO(活动数据对象) ,以便能够使用SQL命令执行数据比较。 它比传统的量程比较(循环)更快。 我不确定它是否比Array to Array比较快,但是一旦你掌握了它,它肯定更容易阅读和调整。 无论如何,这可能有点太多了(因为你说这是你的第一个项目),但这是经过尝试和testing,当然有效。

重要提示:注意sconnectvariables。 您需要根据您的Excel版本使用正确的连接string