查找功能仅在第一时间有效

时间:2019-12-02 00:12:45

标签: excel vba

我在excel中有一个VBA宏,该宏旨在根据特定单元格中的值修改数据。

该单元格由一个下拉框填充,并且是逗号分隔的值列表,例如2,3,43,1,9

当我的宏运行时,它提取值并循环遍历每个值:

LArray = Split(Range("B6").Value, ",")

For count = 0 To UBound(LArray)

    ' the current item we are looking for
    WHAT_TO_FIND = LArray(count)

    ' ... do something

Next

在此循环中,我搜索WHAT_TO_FIND值并对其为1的行进行修改。

此代码已经过测试,所有代码都可以正常工作。此外,如果在单元格中找到第一个值,则所有代码都可以正常工作。但是,随后循环永远找不到任何东西。

例如:如果单元格B6包含2,3,7(并且2和7都存在),则实际上只能找到2个。之后,3将表示找不到返回,7将返回未找到。实际上,如果单元格B6包含3,2,7,则3将返回未找到,2将返回未找到,7将返回未找到。

我觉得很奇怪,只有在第一次使用find函数时,才知道它是什么原因。

请参阅下面的完整功能:

Sub Macro4()
'
' Macro4 Macro
'

'
    Dim WHAT_TO_FIND As String
    Dim cell As Range
    Dim FoundCell As Range
    Dim Percentile As Double
    Dim firstAddress As String

    Dim count As Integer
    Dim LArray() As String

    LArray = Split(Range("B6").Value, ",")


    Percentile = Range("C6").Value

    ' for each part of the list in B6
    ' we will be applying our percentile function
    For count = 0 To UBound(LArray)

        ' the current item we are looking for
        WHAT_TO_FIND = LArray(count)

        ' search in our Decile table (in our Data sheet) A2 to A11
        With Worksheets("Data").Range("A2:A11")

            ' set our FoundCell as the first found item

            Set FoundCell = .Find(What:=WHAT_TO_FIND)

            ' if there exists any
            If Not FoundCell Is Nothing Then

                ' store where we started so we don;t do it twice
                firstAddress = FoundCell.Address
                Do

                    Worksheets("Data").Range("J" & FoundCell.Row).Value = Percentile

                    ' and move to the next
                    Set FoundCell = .FindNext(FoundCell)

                Loop While FoundCell.Address <> firstAddress

            End If

        End With

    Next

End Sub

1 个答案:

答案 0 :(得分:0)

下面是一个简单的宏示例,它遍历范围并检查每个单元格的值是否在数组中;如果找到匹配项,则从当前单元格偏移并粘贴所需的特定单元格中的值。

Dim ws As Worksheet, arr() As String
Set ws = ThisWorkbook.Sheets("Data")

    arr = Split(ws.Range("B6").Value, ",")

        For Each cel In ws.Range("A2:A11")
            For i = LBound(arr) To UBound(arr)
                If cel.Value = arr(i) Then
                    cel.Offset(, 9).Value = ws.Range("C6").Value
                End If
            Next i
        Next cel