2017-05-27 66 views
0

所以我在我的宏中有一个部分,我想添加我认为需要成为“Else”部分的内容,但是我对宏并不擅长,并且正在寻求帮助。如果找不到,再次搜索

Range("Z1").Copy 

Dim FindString As String 
Dim Rng As Range 
FindString = Sheets("Pull").Range("Y1").Value 
If Trim(FindString) <> "" Then 
    With Sheets("HourTracker").Range("A:A") 
     Set Rng = .Find(What:=FindString, _ 
         After:=.Cells(.Cells.Count), _ 
         LookIn:=xlValues, _ 
         LookAt:=xlWhole, _ 
         SearchOrder:=xlByRows, _ 
         SearchDirection:=xlNext, _ 
         MatchCase:=False) 
     If Not Rng Is Nothing Then 
      Application.Goto Rng, True 
     Else 
      MsgBox "Nothing found" 
     End If 
    End With 
      ActiveCell.Offset(0, 1).Activate 
      Selection.PasteSpecial xlPasteValues 
Application.DisplayAlerts = True 
    End If 

End Sub 

所以我想这个做的,是不是“MSGBOX‘未找到’”,我希望它实质上执行与上述相同的事情,但复制单元格Z2,并搜索Y2的值在同一张表“HourTracker”中粘贴该值。我不知道如何做到这一点,而我所有的尝试都失败了。任何帮助将非常感激。让我知道如果你需要更多的澄清,提前谢谢!

回答

0

听起来像你在寻找一个循环。

Sub findStuff() 

Application.DisplayAlerts = False 

' The item you want to paste 
Dim PasteString As String 

' The item you're looking for 
Dim FindString As String 

' The range that may containing FindString 
Dim Rng As Range 

' The variable used to loop through your range 
Dim iCounter as Long 

' loop through the first cell in column Y to the last used cell 
For iCounter = 1 To Sheets("Pull").Cells(Rows.Count, 25).End(xlUp).Row 

    ' PasteString = the current cell in column Z 
    PasteString = Sheets("Pull").Cells(iCounter, 26).Value 

    ' FindString = the current cell in column Y 
    FindString = Sheets("Pull").Cells(iCounter, 25).Value 


    If Trim(FindString) <> "" Then 
     With Sheets("HourTracker").Range("A:A") 

      ' Find the cell containing FindString 
      Set Rng = .Find(What:=FindString, _ 
          After:=.Cells(.Cells.Count), _ 
          LookIn:=xlValues, _ 
          LookAt:=xlWhole, _ 
          SearchOrder:=xlByRows, _ 
          SearchDirection:=xlNext, _ 
          MatchCase:=False) 

      If Not Rng Is Nothing Then 
       ' There's no need to activate/ select the cell. 
       ' You can directly set the value with .Value 
       Rng.Offset(0, 1).Value = PasteString 
      Else 
       ' Do nothing 
      End If 

     End With 
    Else 
     ' Do nothing 
    End If 

Next 

Application.DisplayAlerts = True 

End Sub 

每次编译器击中Next将在For重新开始,但通过提高1.的iCounter值我们可以使用Cells做到这一点,因为Cells需要的行和列参数为数字,而不是字符串(如Range)。语法简单地为Cells(Row #, Column #)。因此,每次For . . . Next再次循环时,iCounter都会增加一个,您将在下一行搜索。

除了使用.Paste,您可以直接使用.Value设置单元格的值。粘贴速度很慢,使用.Value要快得多。

Cells().End(xlUp).Row是一种用来查找范围内最后使用的单元格的方法。请参阅Error in finding last used cell in VBA,这里的解释比我能给出的更好。

相关问题