使用 .Find() 在 for each 循环中查找值

Find values in a for each loop using .Find()

我正在寻找一个循环,它可以为每个匹配的输入值复制值,而不仅仅是停留在它找到的第一个值上。 所以我在一个组合框中输入了一些我想在 2 个工作簿(wb FC 和 CL1)中找到的 ID 号,然后将值复制到它的右边并粘贴到另一个工作簿中。在 FC 中,该值只会出现一次,但在 CL1 中,它可以出现多次。我尝试的循环只针对第一个找到的值来处理它,我希望它为每个匹配的值复制它。

这是我想出的:

Option Explicit


Private Sub CommandButton1_Click()

Dim txt As String, wart As String
Dim offset As Integer
Dim r As Range, c As Range, d As Range, e As Range


txt = txtCo.Text
offset = txtOffset.Text

Set r = Workbooks("FC.xlsx").Worksheets("Arkusz1").Range("A:A")
Set c = r.Find(txt, LookIn:=xlValues)

If c Is Nothing Then
    MsgBox "nieznaleziono"
    Exit Sub

End If

wart = c.offset(0, offset).Text
MsgBox wart

Set d = Worksheets("CL1").Range("B:B")
Set e = d.Find(txt, LookIn:=xlValues)
 
e.offset(0, 18) = wart

End Sub

谢谢

使用 FindNext 查找多个匹配项

  • 请注意 Find method 有更多参数,例如LookAt (全部或部分匹配)这对您的情况至关重要。此外,如果行被隐藏,设置为参数 xlValuesLookIn 参数可能无法找到匹配项。因此,参数 xlFormulas 通常是更安全的选择。
  • FindNext method
Option Explicit

Private Sub CommandButton1_Click()

    Dim txt As String, wart As String
    Dim offset As Long
    Dim r As Range, c As Range, d As Range, e As Range
    
    txt = txtCo.Text
    offset = txtOffset.Text
    
    Set r = Workbooks("FC.xlsx").Worksheets("Arkusz1").Range("A:A")
    Set c = r.Find(txt, LookIn:=xlValues)
    
    If c Is Nothing Then
        MsgBox "nieznaleziono"
        Exit Sub
    End If
    
    wart = c.offset(0, offset).Value
    MsgBox wart
    
    Set d = Worksheets("CL1").Range("B:B")
    Set e = d.Find(txt, LookIn:=xlValues)
     
    Dim FirstAddress As String
    If Not e Is Nothing Then
        FirstAddress = e.Address
        Do
            e.offset(0, 18) = wart
            Set e = d.FindNext(e)
        Loop Until e.Address = FirstAddress
    End If
    
End Sub