遍历数据集并选择数据范围

时间:2019-06-12 11:57:51

标签: excel vba

我在A列中有一组具有投资组合编号的数据。我想创建一个循环通过A列并停止并在出现新的De Portfolio编号时选择数据的宏。

下面有一个例子。

Portfolio   Owner Name
7000107510  Bravo Top B.V.
7000107510  Bravo Top B.V.
7000107510  Bravo Top B.V.
7000107510  Bravo Top B.V.
7000107510  Bravo Top B.V.
7000107510  Bravo Top B.V.
7000107510  Bravo Top B.V.
7000108762  Beheermaatschappij J. de Vrind B.V.
7000108762  Beheermaatschappij J. de Vrind B.V.
7000108762  Beheermaatschappij J. de Vrind B.V.
7000108762  Beheermaatschappij J. de Vrind B.V.
7000108762  Beheermaatschappij J. de Vrind B.V.
7000108762  Beheermaatschappij J. de Vrind B.V.
7000108762  Beheermaatschappij J. de Vrind B.V.

因此,循环选择7000107510并在看到另一个数字(在这种情况下为7000108762)时停止循环。然后,我要选择包含投资组合编号7000107510及其旁边的列的整行数据。

2 个答案:

答案 0 :(得分:1)

由于我们需要在搜索值旁边找到行,因此可以使用xlPrevious方向从底部搜索它。它将找到具有该值的最后一行。向下偏移一行,我们将获得所需的行。

Range("A:A").Find("Portfolio_Number", SearchDIrection:=xlPrevious).Offset(1).EntireRow.Select

答案 1 :(得分:1)

尝试:

    Option Explicit

    Sub test()

        Dim LastRow As Long, i As Long, j As Long, StartPoint As Long
        Dim strValue As String

        strValue = ""
        StartPoint = 2

        'With statement refer to Sheet1. Change if needed
        With ThisWorkbook.Worksheets("Sheet1")

            'Find Last row of column A in Sheet1
            LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

            'Loop starting from row 2 to LastRow variale. Change Starting position if needed
            For i = 2 To LastRow

                If i >= StartPoint Then

                    strValue = .Range("A" & i).Value

                    For j = i + 1 To LastRow

                        If .Range("A" & j).Value <> strValue Then
                            .Range("A" & j - 1 & ":B" & j - 1).Select
                            Exit For
                        End If

                    Next j

                    StartPoint = j

                End If

            Next i

        End With

    End Sub