vba与find和findnext有关的问题

时间:2017-07-24 18:49:36

标签: excel vba excel-vba

我想在工作表Column 5上的BD上搜索与我的工作表alocacao上名为Plan1的某些值匹配的所有条目。然后它应该将Column 2上的值复制到名为tecnico1的单元格(其他单元格称为tecnico2, tecnico3 and tecnico4)。我在下面说明:

enter image description here

值为TESTE 2的单元格为alocacao

enter image description here

enter image description here

我尝试使用Find和FindNext,这是我到目前为止所尝试的:

Sub VerifProd_Click()

Dim FoundCell As Range
Dim LastCell As Range
Dim FirstAddr As String
Dim fnd As String
Dim i As Long

i = 2
fnd = Sheets(1).Range("alocacao").Value

With Sheets("BD").Columns(5)
    Set LastCell = .Cells(.Cells.Count)
End With

Set FoundCell = Sheets("BD").Columns(5).Find(what:=fnd, after:=LastCell)

If Not FoundCell Is Nothing Then
    FirstAddr = FoundCell.Address
End If

Do Until FoundCell Is Nothing
    Sheets("BD").Cells(i,2).Copy Sheets("Plan1").Range("tecnico" & i).Value
    i = i + 1
    Set FoundCell = Sheets("BD").Columns(5).FindNext(after:=FoundCell)
    If FoundCell.Address = FirstAddr Then
        Exit Do
    End If
Loop

End Sub

但它不起作用,我得到运行时错误1004 ,但代码未突出显示。我对Find和FindNext不是很熟悉,所以我很感激任何帮助,以了解为什么它没有正常工作。

修改

我正在尝试新的东西,我改变了它的一部分只是为了测试它会将值粘贴到单元格B26上。现在我得到运行时错误438

With Sheets("BD").Columns(5)
    Set LastCell = .Cells(.Cells.Count)
End With

Set FoundCell = Sheets("BD").Columns(5).Find(what:=fnd, after:=LastCell)

If Not FoundCell Is Nothing Then
    FirstAddr = FoundCell.Address
End If

Do Until FoundCell Is Nothing
    Sheets("Plan1").Range("B26") = FoundCell.Adress.Offset(0, -3).Value

    Set FoundCell = Sheets("BD").Columns(5).FindNext(after:=FoundCell)
    If FoundCell.Address = FirstAddr Then
        Exit Do
    End If
Loop

2 个答案:

答案 0 :(得分:2)

好的假设您在表"Plan1"中有4个名为tecnico1, tecnico2, tecnico3 and tecnico4的已命名单元格,我建议进行以下修改,请注意我们应该停在4匹配的名称范围tecnico

Sub VerifProd_Click()
    Dim FoundCell As Range, FirstAddr As String, fnd As String, i As Long

    fnd = Sheets(1).Range("alocacao").value
    Set FoundCell = Sheets("BD").Columns(5).Find(what:=fnd, _
        After:=Sheets("BD").Cells(Rows.count, 5), Lookat:=xlPart, _
        LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlNext)

    If FoundCell Is Nothing Then Exit Sub
    Do
        i = i + 1
        Sheets("Plan1").Range("tecnico" & i).value = FoundCell.Offset(,-3).Value2
        Set FoundCell = Sheets("BD").Columns(5).FindNext(After:=FoundCell)
    Loop Until FoundCell.Address = FirstAddr Or i >= 4
End Sub

答案 1 :(得分:0)

.Find和.FindNext算法的使用如下......

With Sheets("BD").Columns(5)
    Set FoundCell = .Find(what:=fnd, after:=LastCell)

    If Not FoundCell Is Nothing Then
        FirstAddr = FoundCell.Address
        Do
            Sheets("BD").Cells(i, 2).Copy Sheets("Plan1").Range("tecnico" & i).Value
            i = i + 1
            Set FoundCell = .FindNext(FoundCell)
        Loop While Not FoundCell Is Nothing And FirstAddr <> FoundCell.Address
    End If
End With