如何使用匹配提取范围内的不同值

时间:2019-06-21 09:34:53

标签: excel vba

我需要从包含具有给定值(Range(“ A1”)。Value)的相同值的不同行中提取多个值,并且我想将它们分别提取为(Range(“ B1”)。Value)每次我按下一个按钮(使用宏)。

但是我的代码提取了错误的值。 这是我的代码:

        Dim RowNum As Long, lastrow As Long, colnum As Long
        colnum = 14
        RowNum = 1
        lastrow = cells(ASht("M").Rows.Count, colnum).End(xlUp).Row
l01:
        If Application.WorksheetFunction.CountIf(Range(Cells(RowNum, colnum), Cells(lastrow, colnum)), Range("A1").Value) > 0 Then
            RowNum = Application.WorksheetFunction.Match(Range("A1").Value, Range(Cells(RowNum, colnum), Cells(lastrow, colnum)), 0)

            If Range("B1").Value = "" Then
                Range("B1").Value = cells(RowNum, 4).Value
            Else
                If Range("B1").Value <> cells(RowNum, 4).Value Then
                    Range("B1").Value = cells(RowNum, 4).Value
                Else
                    RowNum = RowNum + 1
                    GoTo l01
                End If
            End If
        Else
            MsgBox "Nothing found", vbInformation
        End If

1 个答案:

答案 0 :(得分:0)

您可能想使用Find而不是工作表功能匹配。也要研究使用循环,而不是“一对一”地运行宏。

看看是否有帮助:

Sub findValue()

    Dim ws As Worksheet: Set ws = ActiveWorkbook.Sheets("Sheet1") '<-- change name here
    Dim rowNum As Long, lastRow As Long, colNum As Long
    colNum = 14
    rowNum = 1
    lastRow = ws.Cells(Rows.Count, colNum).End(xlUp).Row

    Dim rngFind As Range
    With ws
        Set rngFind = .Range(.Cells(rowNum, colNum), .Cells(lastRow, colNum)).Find(.Range("A1").Value)
        If Not rngFind Is Nothing Then
            .Range("B1").Value = .Cells(rngFind.Row, 4)
        Else
            MsgBox "Nothing found", vbInformation
        End If
    End With
End Sub

PS:我删除了内部if条件,因为据我所知,无论结果如何,您都在做相同的事情。

Range("B1").Value将为空,或者不等于cells(RowNum, 4).Value,无论如何您都在写值。如果它们是匹配的...那么,值已经存在。也许我在这种逻辑中缺少某些东西。