修改宏以进行列搜索

时间:2017-04-06 14:58:45

标签: excel vba excel-vba

我有一个宏,直到现在才用于从F列搜索一个单元格,但现在我必须搜索F列中的所有单元格。如果在F中找到值N:AN,offset(f,0) ,1)必须具有单元格值(找到行,列AI)。

Sub find()
    Dim FindString As String
    Dim Rng As Range
    FindString = Sheets("Sheet1").Range("f48").Value
    If Trim(FindString) <> "" Then
        With Sheets("Sheet1").Range("n:an")
            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
                Sheets("Sheet1").Range("f48").Offset(0, 1).Value = Rng.Offset(0, 21).Value
            Else
                Sheets("Sheet1").Range("f48").Offset(0, 1).Value = "Nothing found"
            End If
        End With
    End If
End Sub

2 个答案:

答案 0 :(得分:1)

也许是这样,如果我理解正确的话(假设F中的值最多只能找到一次)。

Sub find()

Dim Rng As Range
Dim r As Range

With Sheets("Sheet1")
    For Each r In .Range("F1", .Range("F" & .Rows.Count).End(xlUp))
        If Trim(r) <> vbNullString Then
            With .Range("n:an")
                Set Rng = .find(What:=r.Value, _
                                LookAt:=xlWhole, _
                                MatchCase:=False)
                If Not Rng Is Nothing Then
                    r.Offset(0, 1).Value = .Cells(Rng.Row, "AI").Value
        'Else
        '    Sheets("Sheet1").Range("f48").Offset(0, 1).Value = "Nothing found"
                End If
           End With        
        End If
     Next r
End With

End Sub

答案 1 :(得分:1)

看看这是否有用。它有点变化,但我认为它可能更干净:)

当你发现&#34;当然,你需要根据你的偏移标准进行调整。 N:NA范围内的匹配

Sub Dougsloop()

Dim rCell As Range
Dim rRng As Range
Dim wsO As Worksheet
Dim aRR As Variant

Set wsO = ThisWorkbook.Sheets("Sheet1")

aRR = wsO.UsedRange.Columns("N:NA")

Set rRng = ThisWorkbook.Sheets("Sheet1").Range("F1:F500")
For Each rCell In rRng.Cells
    If Trim(rCell.Value) <> vbNullString Then
        thisValue = rCell.Value
        If IsError(Application.Match(aRR, thisValue, 0)) = True Then
            'Generic Eror Handling
        ElseIf IsError(Application.Match(aRR, thisValue, 0)) = False Then
            'Stuff you do when you find the match
            rCell.Offset(0, 1).Value = "found it"
        End If
    End If
Next rCell

End Sub