vba 根据另一个单元格中的条件将单元格从一个工作表复制到另一个工作表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25876099/
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 04:33:32  来源:igfitidea点击:

Copy cells from one sheet to another based on criteria in another cell

excelvbaexcel-vba

提问by Justin_DavieHigh

I am wanting to use VBA to copy cells from one sheet to another sheet in the same workbook based on if the criteria of certain cells match in both sheets.

我想使用 VBA 将单元格从一张工作表复制到同一工作簿中的另一张工作表,这取决于某些单元格的条件是否在两个工作表中都匹配。

Example: If Sheet1!A1 = Sheet2!A1 Then Copy Sheet1!B1 To Sheet2!B2

示例:如果 Sheet1!A1 = Sheet2!A1 然后将 Sheet1!B1 复制到 Sheet2!B2

I could do it via a function: =IF($A1=Sheet1!$A1, VLOOKUP(Sheet1!$A1, Sheet1!$A1:$D1, 2),"")but am at a loss to make it work in VBA. I thought about an IF|ELSE Statement but couldn't get it to work.

我可以通过一个函数来做到这一点:=IF($A1=Sheet1!$A1, VLOOKUP(Sheet1!$A1, Sheet1!$A1:$D1, 2),"")但是我无法让它在 VBA 中工作。我想过 IF|ELSE 语句,但无法让它发挥作用。

回答by user184994

This should work for you:

这应该适合你:

For Counter = 1 To 10 
    If Sheets(1).Range("A" & Counter).Value = Sheets(2).Range("A" & Counter).Value Then
        Sheets(2).Range("B" & (Counter + 1)).Value = Sheets(1).Range("B" & Counter).Value
    End If
Next Counter

回答by hedgedandlevered

Sub copyToSheet()
For i = 1 To 10
    If ThisWorkbook.Worksheets("sheet1").Range("A1").Offset(i - 1, 0).Value = ThisWorkbook.Worksheets("sheet2").Range("A1").Offset(i - 1, 0).Value Then
    ThisWorkbook.Worksheets("sheet2").Range("A1").Offset(i - 1, 1) = ThisWorkbook.Worksheets("sheet1").Range("A1").Offset(i - 1, 0).Value
    End If
    Next i
End Sub