【问题标题】:Find values in a for each loop using .Find()使用 .Find() 在每个循环中查找值
【发布时间】:2021-04-15 09:27:10
【问题描述】:

我正在寻找一个循环来复制每个匹配输入值的值,而不仅仅是停留在它找到的第一个。 因此,我在一个组合框中输入了一些我想在 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

谢谢

【问题讨论】:

  • 您使用FIND 查找第一个值,但没有使用FindNext 查找任何后续值。查看MS example - 检查c is not nothing,然后检查r.FindNext(c)

标签: excel vba loops skip


【解决方案1】:

使用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

【讨论】:

  • 是的,这正是我想要的。我把循环放在错误的地方。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-07
  • 2015-01-26
  • 2019-02-19
  • 2023-03-15
相关资源
最近更新 更多