VBA查找和findnext来粘贴值

如果Plan1的值与Column 5上的单元格匹配,则在此表中我想使用FindFindNext来search另一个工作表BD上的值,并将它们复制到主工作表Plan1

我曾经有4个命名范围tecnico1, tecnico2, tecnico3 and tecnico4来粘贴值和代码工作正常。

这是它的样子:

在这里输入图像说明

和BD表:

在这里输入图像说明

这是代码:

 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).Value Sheets("Plan1").Range("upps0" & i).Value = FoundCell.Offset(, -1).Value Set FoundCell = Sheets("BD").Columns(5).FindNext(After:=FoundCell) Loop Until FoundCell.Address = FirstAddr Or i >= 4 End Sub 

但是,现在我意识到我需要更多的领域,因为我可能会插入超过4 tecnicosalocacao 。 所以现在看起来如此:

在这里输入图像说明

而我只是改变了这部分代码:

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

所以我期待它只填充4场,因为我还只有4场比赛,但是我得到了这个结果:

在这里输入图像说明

由于我是使用Find和FindNext的新手,我真的不知道我必须改变什么来填充单元格而不用重复。

任何build议将有所帮助! 也许有什么我不能注意到那里。

我只是使用@Luuklag的build议,现在它正在工作。

 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 Not FoundCell Is Nothing Then FirstAddr = FoundCell.Address End If If FoundCell Is Nothing Then Exit Sub Do i = i + 1 Sheets("Plan1").Range("tecnico" & i).Value = FoundCell.Offset(, -3).Value Sheets("Plan1").Range("upps0" & i).Value = FoundCell.Offset(, -1).Value Set FoundCell = Sheets("BD").Columns(5).FindNext(After:=FoundCell) Loop Until FoundCell.Address = FirstAddr Or i >= 10 End Sub