需要一个宏来搜索并将记录从一个工作表更新到另一个工作表

时间:2015-03-07 15:35:15

标签: excel vba excel-vba excel-2010

我需要一个宏代码来搜索单元格1到1000中的sheet1的内容(可能是数字或aplhanumeric),并从sheet2中搜索相同的文本。如果它发现然后我需要更新相邻单元格对应的内容。 例如:

sheet1
1024     D
505A
6057     C




sheet2
1024     D
6057     C

1 个答案:

答案 0 :(得分:0)

假设查找值在A列中,并且要复制的值在B列中。

Sub FindValues()

Dim lookUpSheet As Worksheet, updateSheet As Worksheet
Dim valueToSearch As String
Dim i As Integer, t As Integer

Set lookUpSheet = Worksheets("sheet1")
Set updateSheet = Worksheets("sheet2")

'get the number of the last row with data in sheet1 and in sheet2
lastRowLookup = lookUpSheet.Cells(Rows.Count, "A").End(xlUp).Row
lastRowUpdate = updateSheet.Cells(Rows.Count, "A").End(xlUp).Row

'for every value in column A of sheet2
For i = 1 To lastRowUpdate
     valueToSearch = updateSheet.Cells(i, 1)
     'look the value in column A of sheet1
     For t = 1 To lastRowLookup
        'if found a match, copy column B value to sheet1 and proceed to the next value
        If lookUpSheet.Cells(t, 1) = valueToSearch Then
            updateSheet.Cells(i, 2) = lookUpSheet.Cells(t, 2)
            Exit For
        End If
     Next t
Next i

End Sub