【发布时间】:2021-02-25 17:21:39
【问题描述】:
对于 Sheet("Scrap2") A 列中的每个值。
在 Sheet("VA_Data") 的 A 列中找到该值的所有匹配实例。复制整行并粘贴到工作表上的第一个空行(“列表”)
我的代码现在基本上只复制匹配的第一个实例,然后移动到 Sheet("Scrap2") 中的下一个值。
如果工作表“VA_Data”的 col A 中有 10 个单元格与 Scrap2 的第一个值匹配,则这 10 行需要复制整行并粘贴到工作表“List”上的第一个空行。
感谢任何帮助。
Option Explicit
Public Sub Loop_VA_Data()
Dim wsa As Worksheet
Dim wsb As Worksheet
Dim wsc As Worksheet
Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim stra As String
Dim rng As Range
On Error GoTo errLoop_VA_Data
Application.ScreenUpdating = False
Set wsa = ThisWorkbook.Worksheets("Scrap2")
Set wsb = ThisWorkbook.Worksheets("VA_Data")
Set wsc = ThisWorkbook.Worksheets("List")
wsa.Range("B:B").Clear
wsc.Rows("2:" & wsc.Range("A1").CurrentRegion.Rows.Count + 1).Clear
a = 2
Do
If Trim(wsa.Cells(a, 1).Value) = "" Then
Exit Do
End If
stra = Trim(wsa.Cells(a, 1).Value)
Set rng = wsb.Range("A:A").Find(What:=stra, LookIn:=xlValues, LookAt:=xlWhole)
If Not (rng Is Nothing) Then
b = rng.Row
c = wsc.Range("A1").CurrentRegion.Rows.Count + 1
wsb.Rows(b).Copy wsc.Rows(c)
wsa.Cells(a, 2).Value = "Found on row " & b
Else
wsa.Cells(a, 2).Value = "Not Found"
End If
If Not (rng Is Nothing) Then
Set rng = Nothing
End If
a = a + 1
Loop
MsgBox "Complete!", vbInformation
GoTo closeout
Exit Sub
errLoop_VA_Data:
MsgBox "Err Number is: " & Err.Number & " / Err Desc is: " & Err.Description & " in sub Loop_VA_Data!", vbCritical
closeout:
If Not (wsa Is Nothing) Then
Set wsa = Nothing
End If
If Not (wsb Is Nothing) Then
Set wsb = Nothing
End If
If Not (wsc Is Nothing) Then
Set wsc = Nothing
End If
If Not (rng Is Nothing) Then
Set rng = Nothing
End If
Exit Sub
End Sub
【问题讨论】:
-
过滤器在这里会更好,即
Filter作为您的目标值,然后使用结果可见范围(xlCellTypeVisible) -
您需要使用
FindNext来查找更多实例。您还应该摆脱隐藏问题的 Goto 和 On Errors。 -
你能告诉我如何将 FindNext 合并到我的代码中吗?