VBA 查找第 1 行中的文本。如果大于零,则复制并粘贴到行下方

VBA Find Text in Row 1. Copy & paste below rows if greater than zero

我有一个代码可以在第 1 行中搜索文本字符串。搜索没有问题。

问题

找到文本后,我需要宏在列中搜索大于零的值,如果找到则复制整行并粘贴到 sheet 2。所以我没有成功。

请看下面的代码:

Private Sub btnUpdateEntry_Click()

    Dim StringToFind As String
Dim i As Range
    StringToFind = Application.InputBox("Enter string to find", "Find string")

    Worksheets("Skills Matrix").Activate
    ActiveSheet.Rows(1).Select

        Set cell = Selection.Find(What:=StringToFind, After:=ActiveCell, _
        LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)


    For Each i In cell
        If i.Value > 0 Then
            i.Select
            ActiveCell.Range("1:1").EntireRow.Select
            Selection.Copy
            Sheets("Sheet2").Range("A65000").End(xlUp).Offset(1, 0).PasteSpecial
        End If
    Next i

    If cell Is Nothing Then
        Worksheets("Data").Activate
        MsgBox "String not found"
    End If

End Sub

谢谢。

尝试一下,虽然我怀疑您是否需要搜索整个列?您的循环仅搜索一个单元格。如果可以在第一行中多次找到搜索字符串,则需要修改此代码。

Private Sub btnUpdateEntry_Click()

Dim StringToFind As String
Dim i As Range
Dim cell As Range

StringToFind = Application.InputBox("Enter string to find", "Find string")

With Worksheets("Skills Matrix")
    Set cell = .Rows(1).Find(What:=StringToFind, LookAt:=xlWhole, _
                             MatchCase:=False, SearchFormat:=False)

    If Not cell Is Nothing Then
        For Each i In .Range(cell.Offset(1), .Cells(.Rows.Count, cell.Column).End(xlUp))
            If IsNumeric(i.Value) Then
                If i.Value > 0 Then
                    i.EntireRow.Copy
                    Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial
                End If
            End If
        Next i
    Else
        Worksheets("Data").Activate
        MsgBox "String not found"
    End If
End With

End Sub

您需要显式编写才能搜索 ByRows

Set cell = .Rows(1).Find(What:=StringToFind, LookAt:=xlWhole, SearchOrder:=xlByRows, 
                             MatchCase:=False, SearchFormat:=False)