使用Excel VBA循环一个工作表中的项目,匹配另一个工作表并复制值

问题描述 投票:0回答:1

我已经完成了85%,但最后一部分却被困住了。我有2张。其中一个包含价格,描述等的订单项。另一个包含具有与其关联的单价的商品的主列表。我的代码在下面找到了从sheet1到sheet2的正确匹配。我试图从第2列中的sheet2获得单价。所以基本上来自sheet1 C列的项目与sheet2列A中的列表匹配。当找到匹配时,我需要sheet2列B中的值匹配的行。如果您能提供帮助或需要进一步解释,请与我们联系。这真让我抓狂。有点像VBA的新手。谢谢!

Sub test2()
Dim r1 As Range
Dim r2 As Range
Dim cell As Range
Dim lastrow As Long



With ThisWorkbook.Worksheets("Sheet1")
    lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row
    Set r1 = .Range("C2:C" & lastrow)
End With




With ThisWorkbook.Worksheets("Sheet2")
    lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    Set r2 = .Range("A1:A" & lastrow)
End With


For Each cell In r1
    If IsError(Application.Match(cell, r2, 0)) Then
        cell.Offset(, 15) = "NotFound"
    Else
        cell.Offset(, 15) = "Found"
        ' If found I need the value from Sheet2 that is in Col B of the matching row.
    End If
Next cell




End Sub

表1 可乐 第1项 第2项 第3项

表2 Col A Col B. 第1项1.99 第2项2.99 项目3 3.99

我试图在第一张中循环Col A并匹配sheet2中的相应值并将价格(sheet2的ColB)复制到sheet1

excel vba loops match
1个回答
0
投票

这是你想要得到的吗?:

    ' If found I need the value from Sheet2 that is in Col B of the matching 
With ThisWorkbook
.Sheets("Sheet1").Cells(cell.Row, 2).Value =.Sheets("Sheet2").Cells(Application.Match(cell, r2, 0), 2).Value
End With
© www.soinside.com 2019 - 2024. All rights reserved.