通过查找匹配的键值来更新值

对于你们许多人来说,这可能很容易,但我是VBA的新手; 以下是我的代码将多个Excel文件值添加到一个主表。 虽然我这样做,我想更新关键的价值观。

Sub tekSheetMerging() Dim masterSheet As Worksheet Set masterSheet = sheets("KoMKo") 'Variable to save the used Range of the master sheet Dim usedRangeMaster As Integer Dim ws As Worksheet 'loop through each worksheet in current workbook For Each ws In Worksheets 'If sheetname contains "data" (UCase casts the Name to upper case letters) If InStr(1, UCase(ws.Name), "DATA", vbTextCompare) > 0 Then 'calculate the used range of the master sheet usedRangeMaster = masterSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1 'Variable to save the used Range of the sub sheet Dim usedRangeSub As Integer 'calculate the used range of the sub sheet usedRangeSub = ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row 'copy relevant range from the subsheet ws.Range("C1:C" & usedRangeSub).Copy 'paste the copied range after the used range in column a masterSheet.Range("A" & usedRangeMaster).PasteSpecial End If Next ws End Sub 

所以,现在我有一个Excel表,其中包括在列A中的键值和在该行中的其他列中的其他值。 当我find一个键是重复的键值,这是之前添加的,我想删除该单元格及其完整的行。 通过这样做,我想更新值,关于他们的关键价值。 如果我将添加另一个键,它应该留在列表中,但没有问题。

我怎样才能做到这一点?

首先通过子表单(源)中的键并逐一比较主键中的键。 任何比赛都应该从主控中删除。 然后,将子表单中的全部数据复制到主表中。

我的代码因此在这行之前:

 'copy relevant range from the subsheet ws.Range("C1:C" & usedRangeSub).Copy 

用你的我的variablesreplace:

 With mastersheet for i = firstrow to lastrow 'first and lastrow of data in subsheet set f = .Range("A:A").Find(ws.Range("A" & i).Value, _ LookIn:=xlValues, LookAt:=xlWhole) If Not f is Nothing then .Range("A" & f.Row).EntireRow.Delete End If next i end with 

此后不要忘记更新usedRangeMaster,因为删除会更短。 然后复制粘贴你的数据。

注意:这段代码假定你的密钥是唯一的,你将永远不会有重复在你的主(这将是这种情况下,如果主人只能通过这个代码)。 这就是为什么它只search一次主人。

编辑:我看到freakfeuer已经提供了一些链接? 无论如何,让我知道如果它的作品。