查找列中的所有值并检索数组中的地址

时间:2016-07-29 12:53:57

标签: excel vba

我想在VBA中使用.find函数来查找列中值的实例,但是根据与找到值的行相同的条件进行计算。这是有问题的,因为虽然我正在寻找的值可能相同,但用于创建总分的标准是不同的。因此,我需要循环遍历列中的所有值,我想知道如何在vba中执行此操作。我知道findnext函数,但我永远无法正常工作。

 counted = Application.WorksheetFunction.CountIfs(cl.Range(finletter & "9:" & finletter & "317"), "Value", cl.Range("H9:H317"), wl.Range("A" & y.row).Value)
        'Pol small low complex
        If counted > 0 Then
            MsgBox wl.Range("A" & y.row).Value
        If cl.Range("C" & y.row).Value < 3 And cl.Range("D" & y.row).Value = 1 And cl.Range("E" & y.row).Value = "Interim" Then

        wl.Range(y.Address) = 3.75 * counted

1 个答案:

答案 0 :(得分:1)

这是一个例子。假设我们正在 A 列中查找文本“LOVE”并处理这些行上的数据:

Option Base 1

Sub LookingForLove()
    Dim s As String, rng As Range, WhichRows() As Long
    Dim rFound As Range

    ReDim WhichRows(1)

    s = "LOVE"
    Set rng = Range("A1:A25")
    Set rFound = rng.Find(What:=s, After:=rng(1))
    WhichRows(1) = rFound.Row

    Do
        Set rFound = rng.FindNext(After:=rFound)
        If rFound.Row = WhichRows(1) Then Exit Do
        ReDim Preserve WhichRows(UBound(WhichRows) + 1)
        WhichRows(UBound(WhichRows)) = rFound.Row
    Loop

    msg = UBound(WhichRows) & vbCrLf & vbCrLf
    For i = 1 To UBound(WhichRows)
        msg = msg & WhichRows(i) & vbCrLf
    Next i

    MsgBox msg
End Sub

enter image description here

注:

  • Exit Do阻止永远循环
  • 您的代码将继续循环WhichRows()的元素并处理这些行上的项目。
  • 您的代码也可以创建范围或单元格地址的动态数组。

另一种替代方法是使用 VBA 建立 AutoFilter 并处理可见行。