当两列中的值匹配时,vba 复制特定单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26933595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:14:30  来源:igfitidea点击:

vba to copy specific cells when values from two columns match

excelvbaexcel-vba

提问by Allan B

I'm new to vba and need to find a way to copy certain cells between worksheets based on matching values. In sheet1, column A is a list of abbreviated names. I need to search sheet 2, column D for any matches. If a match is found, copy the cells in A, B, and C of sheet 2 and paste them into the corresponding location in sheet 1.

我是 vba 的新手,需要找到一种方法来根据匹配值在工作表之间复制某些单元格。在 sheet1 中,A 列是缩写名称列表。我需要在第 2 页的 D 列中搜索任何匹配项。如果找到匹配项,请复制工作表 2 的 A、B 和 C 中的单元格并将它们粘贴到工作表 1 中的相应位置。

回答by Golemic

I also believe that the easiest way is using vlookup. Might faster too... You can use something like this if you like. Haven't check it though.

我也相信最简单的方法是使用 vlookup。也可能更快......如果你愿意,你可以使用这样的东西。不过没查过。

Sub CopyBasedonSheet1()

Dim i As Long
Dim j As Long
Sheet1LastRow = Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
Sheet2LastRow = Worksheets("Sheet2").Range("D" & Rows.Count).End(xlUp).Row

    For j = 1 To Sheet1LastRow
        For i = 1 To Sheet2LastRow
            If  Worksheets("Sheet1").Cells(j, 1).Value  = Worksheets("Sheet2").Cells(i, 4).Value Then
                Worksheets("Sheet1").Cells(j, 2).Value  = Worksheets("Sheet2").Cells(i, 1).Value
                Worksheets("Sheet1").Cells(j, 3).Value  = Worksheets("Sheet2").Cells(i, 2).Value
                Worksheets("Sheet1").Cells(j, 4).Value  = Worksheets("Sheet2").Cells(i, 3).Value
            Else
            End If
    Next i
Next j
End Sub