在excel中搜索文本,使用偏移量,然后使用逻辑测试来输出文本字符串

时间:2018-02-07 18:34:42

标签: excel vba excel-vba

这样做的主要目的是搜索" MRQ",一次" MRQ"发现代码做了一行偏移,然后测试产品是否>基准然后输出" over"否则输出" Under"

这是我到目前为止的代码,但是我在输入第二个if子句时遇到了问题。

Sub FindMRQ()

Dim Sh As Worksheet
Dim MRQ As Range
Dim Product As Range
Dim Benchmark As Range

For Each Sh In ThisWorkbook.Worksheets
    With Sh.UsedRange

        Set MRQ = .Cells.Find(What:="MRQ")
        If Not MRQ Is Nothing Then
            MRQ.Offset(rowOffset:=1, columnOffset:=0).Activate
            Do Until MRQ Is Nothing
                    ActiveCell.Value = "YAY!"
                Set MRQ = .FindNext(MRQ)
            Loop
        End If

        'If Product.Range > Benchmark.Range Then
        '"Outperformed" Else
        'If Product.Range < Benchmark.Range Then
        '"Underperformed"
        ' End If


    End With
    Set MRQ = Nothing
Next

End Sub

数据集的示例

2 个答案:

答案 0 :(得分:0)

您需要做的是将If块放在Do Until循环之前,但是在选择要检查的单元格之后。像这样:

Sub FindMRQ()
    Dim Sh As Worksheet
    Dim MRQ As Range
    Dim Product As Range
    Dim Benchmark As Range

    For Each Sh In ThisWorkbook.Worksheets
        With Sh.UsedRange

            Set MRQ = .Cells.Find(What:="MRQ")
            If Not MRQ Is Nothing Then
                MRQ.Offset(rowOffset:=1, columnOffset:=0).Select
                If MRQ.Value > Benchmark.Value Then
                    MsgBox "Outperformed"
                ElseIf MRQ.Value < Benchmark.Value Then
                    MsgBox "Underperformed"
                End If
                Do Until MRQ Is Nothing
                        ActiveCell.Value = "YAY!"
                    Set MRQ = .FindNext(MRQ)
                Loop
            End If
        End With
        Set MRQ = Nothing
    Next Sh
End Sub

你可能仍需要调整它以使其完全正确。

答案 1 :(得分:0)

您可以使用公式代替VBA:

=IF(HLOOKUP("MQR",$A$1:$D$4,MATCH("Product",$A$1:$A$4,0),0)>HLOOKUP("MQR",$A$1:$D$4,MATCH("Benchmark",$A$1:$A$4,0),0),"Outperformed","Underperformed")