Excel VBA使用Find更新不同工作表中的数据
我正在尝试创建一个宏,它允许我比较两个工作表中的数据,并根据任何差异(更新、插入、删除等)进行更新。到目前为止,这就是我所拥有的——但它一直被呼叫Find的电话线所捕获。我已经阅读了很多关于如何做到这一点的教程,但还没有弄清楚如何在工作表之间调用它并使其正确工作。这是我的密码:Excel VBA使用Find更新不同工作表中的数据,vba,excel,Vba,Excel,我正在尝试创建一个宏,它允许我比较两个工作表中的数据,并根据任何差异(更新、插入、删除等)进行更新。到目前为止,这就是我所拥有的——但它一直被呼叫Find的电话线所捕获。我已经阅读了很多关于如何做到这一点的教程,但还没有弄清楚如何在工作表之间调用它并使其正确工作。这是我的密码: Sub Process() 'loop through Intermediate sheet Dim DataRange As Range, UpdateRange As Range, orig As R
Sub Process()
'loop through Intermediate sheet
Dim DataRange As Range, UpdateRange As Range, orig As Range, nov As Range
Dim lastIntRow As Long, lastDocRow As Long, firstEmptyRow As Long
lastIntRow = Sheets("Intermediate").Range("A65536").End(xlUp).Row
lastDocRow = Sheets("Document Library").Range("A65536").End(xlUp).Row
Set DataRange = Sheets("Intermediate").Range(Sheets("Intermediate").Cells(2, 1), Sheets("Intermediate").Cells(lastIntRow, 1))
Set UpdateRange = Sheets("Document Library").Range(Sheets("Document Library").Cells(2, 1), Sheets("Document Library").Cells(lastDocRow, 1))
For Each orig In DataRange
Set nov = UpdateRange.Find(What:=orig)
If nov Is Nothing Then
firstEmptyRow = lastDocRow + 1
Sheets("Document Library").Cells(firstEmptyRow, 1).Value = orig.Value
Sheets("Document Library").Cells(firstEmptyRow, 2).Value = Sheets("Intermediate").Cells(orig.Row, 2).Value
Sheets("Document Library").Cells(firstEmptyRow, 3).Value = Sheets("Intermediate").Cells(orig.Row, 3).Value
Else:
Sheets("Document Library").Cells(nov.Row, 2).Value = Sheets("Intermediate").Cells(orig.Row, 2).Value
Sheets("Document Library").Cells(nov.Row, 3).Value = Sheets("Intermediate").Cells(orig.Row, 3).Value
End If
Next
End Sub
任何帮助都将不胜感激。我真的不知道如何正确地做到这一点,我觉得它只是越来越复杂。谢谢大家! 如果你对“不断被抓到”有更具体的描述,这会很有帮助。错误消息是什么?如果我创建了一个
工作簿
,其中包含代码中提到的两个工作表,并且每个工作表的第一列中都有一些文本,那么我可以毫无困难地运行您的代码。
Sub Process()
'loop through Intermediate sheet
Dim DataRange As Range, UpdateRange As Range, orig As Range, nov As Range
Dim lastIntRow As Long, lastDocRow As Long, firstEmptyRow As Long
Dim shtInt As Worksheet, shtDoc As Worksheet
Dim rw As Range
'using sheet variables de-clutters your code...
Set shtInt = ActiveWorkbook.Sheets("Intermediate")
Set shtDoc = ActiveWorkbook.Sheets("Document Library")
lastIntRow = shtInt.Range("A65536").End(xlUp).Row
lastDocRow = shtDoc.Range("A65536").End(xlUp).Row
firstEmptyRow = lastDocRow + 1 'outside your loop!
Set DataRange = shtInt.Range(shtInt.Cells(2, 1), shtInt.Cells(lastIntRow, 1))
Set UpdateRange = shtDoc.Range(shtDoc.Cells(2, 1), shtDoc.Cells(lastDocRow, 1))
For Each orig In DataRange.Cells
'be more explicit with "Find()"
Set nov = UpdateRange.Find(What:=orig, LookIn:=xlValues, lookat:=xlWhole)
If nov Is Nothing Then
Set rw = shtDoc.Rows(firstEmptyRow)
firstEmptyRow = firstEmptyRow + 1 'set next empty...
rw.Cells(1).Value = orig.Value
Else
Set rw = nov.EntireRow
End If
rw.Cells(2).Value = orig.Offset(0, 1).Value
rw.Cells(3).Value = orig.Offset(0, 2).Value
Next
End Sub