找不到再搜索

Search again if not found

所以我在我的宏中有一个部分,我想添加我认为需要成为 "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 "Nothing Found"",我希望它基本上执行与上面相同的事情,但复制单元格 Z2,并搜索 Y2 的值在同一个 sheet "HourTracker" 中,然后粘贴该值。我不知道如何做到这一点,我所有的尝试都失败了。任何帮助将非常感激。如果您需要更多说明,请告诉我,提前致谢!!!

我觉得你在找循环。

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 开始,但将 iCounter 的值增加 1。我们可以使用 Cells 来完成此操作,因为Cells 将行和列参数作为数字,而不是字符串(如 Range)。语法很简单 Cells(Row #, Column #)。因此,每次 For . . . Next 再次循环时,iCounter 将增加一个,您将在下一行中搜索。

您可以直接使用 .Value 设置单元格的值,而不是使用 .Paste。粘贴非常慢,使用 .Value 会快得多。

Cells().End(xlUp).Row 是一种用于查找区域中最后使用的单元格的方法。请参阅 Error in finding last used cell in VBA 以获得比我在这里给出的更好的解释。