excel 如何在vba中循环遍历一个工作表上的列,查找值并替换为另一个工作表上的值

wztqucjr  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(198)

问题:将sheet1上的列中的值更改为与sheet2上的列中的关联键相匹配的值。
表1:

A
71.81
68.07
68.07
...

Sheet2:键:值对:

A(Key)  B(value)
0   50
1   51.37
2   52.69
3   54.04
4   55.43
5   56.85
6   58.31
7   59.8
8   61.33
9   62.9
10  64.52
20  68.07
30  71.81
40  75
50  79.39
60  83.76
70  88.36
80  93.22
90  98.35
100 100
110 100
120 100
130 100
140 100
150 100
160 100
170 100
180 100
190 100
200 100
201 100

``
-----

expected outcome: 
30
20
20

我有一些落在我脸上的企图,那是不值一提的。

tpxzln5u

tpxzln5u1#

替换为匹配项

  • 为了简单起见,假设范围具有至少两行数据。
Sub ReplaceWithMatches()
    
    ' 1.) Read
    
    ' Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook
    
    ' Source
    Dim sws As Worksheet: Set sws = wb.Worksheets("Sheet2")
    Dim srg As Range
    Set srg = sws.Range("A2", sws.Cells(sws.Rows.Count, "B").End(xlUp))
    Dim slrg As Range: Set slrg = srg.Columns(2) ' lookup
    Dim svData() As Variant: svData = srg.Columns(1).Value ' value
    
    ' Destination
    Dim dws As Worksheet: Set dws = wb.Worksheets("Sheet1")
    Dim drg As Range
    Set drg = dws.Range("A2", dws.Cells(dws.Rows.Count, "A").End(xlUp))
    Dim dData() As Variant: dData = drg.Value ' lookup & value
    
    ' 2.) Modify
    
    ' Loop
    Dim srIndex As Variant ' could be an error value
    Dim dr As Long
    For dr = 1 To UBound(dData, 1)
        srIndex = Application.Match(dData(dr, 1), slrg, 0)
        If IsNumeric(srIndex) Then ' match found
            dData(dr, 1) = svData(srIndex, 1)
        'Else ' no match found; do nothing?
        End If
    Next dr
    
    ' 3.) Write
    
    ' Result
    drg.Value = dData

End Sub

相关问题