程序复制和粘贴两次

我创build了一个macros,允许我search现有的工作表以在单元格值下进行search。

If wS.Name = "2012" Or "2013" Or "2014" Or "2015" Or "2016" Or "2017" Or "2018" Or "2019" Or "2020" Then lastrow = wS.Cells(wS.Rows.count, "B").End(xlUp).Row 'LastRow means to search till the end For r = 2 To lastrow 'This will check entire column for value If wS.Range("B" & r).value = Sheets("Query").Range("A2").value Then wS.Rows(r & ":" & r).Copy Sheets("Male").Range("A65536").End(xlUp).Offset(1) End If Next r 'Exit For End If Next 

我对上面的代码有问题,它复制行两次。 例:

 1/1/2000 | 12345 | 100 2/1/2000 | 12345 | 191 3/1/2000 | 12345 | 211 1/1/2000 | 12345 | 100 2/1/2000 | 12345 | 191 3/1/2000 | 12345 | 211 

你的代码的第一个问题是在这一行:

 If wS.Name = "2012" Or "2013" Or "2014" Or "2015" Or "2016" Or "2017" Or "2018" Or "2019" Or "2020" Then 

Vba没有这种语法的理解

所以,应该是:

 If wS.Name = "2012" Or wS.Name = "2013" Or wS.Name = "2014" Or _ wS.Name = "2015" Or wS.Name = "2016" Or wS.Name = "2017" Or _ wS.Name = "2018" Or wS.Name = "2019" Or wS.Name = "2020" Then 

或者你可以使用这个方法:

 If "|2012|2013|2014|2015|2016|2017|2018|2019|2020|" Like "*|" & wS.Name & "|*" Then 

或者像这样:

 If wS.Name Like "201[2-9]" Or wS.Name = "2020" Then 

最后 ,如果我有正确的理解你想在你的代码中实现什么,那么你可以使用这个:

 For Each wS In ThisWorkbook.Worksheets If "|2012|2013|2014|2015|2016|2017|2018|2019|2020|" Like "*|" & wS.Name & "|*" Then lastrow = wS.Cells(wS.Rows.Count, "B").End(xlUp).Row For r = 2 To lastrow With Sheets("Male") If wS.Range("B" & r).Value = Sheets("Query").[A2].Value Then wS.Rows(r).Copy .Rows(.Cells(Rows.Count, "A").End(xlUp).Row + 1) End If End With Next r End If Next