我创建了一个宏,允许我搜索现有的工作表,以便在单元格值下搜索。
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
答案 0 :(得分:4)
您的代码的第一个问题就在这一行:
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