【问题标题】:Modify macro for column search修改用于列搜索的宏
【发布时间】:2017-04-06 14:58:45
【问题描述】:

我有一个宏,到目前为止,它仅用于从 F 列中搜索一个单元格,但现在我必须搜索 F 列中的所有单元格。如果在 N:AN 范围内找到 F 中的值,则 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

【问题讨论】:

    标签: vba excel


    【解决方案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
    

    【讨论】:

    • 糟糕,漏掉了一行 - 现已修正。
    【解决方案2】:

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

    当然,一旦在 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
    

    【讨论】:

    • 您好,感谢您的回答 - 将来很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2018-05-27
    • 2017-10-22
    • 2016-12-09
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多