迭代一个范围,直到在VBA中找到不同的值

时间:2016-11-11 16:36:38

标签: excel vba excel-vba

我正在尝试创建一个从范围底部开始的VBA函数,并返回与底部值不同的第一个值。

示例:

Sample Excel Table

在上表中,我希望能够获取“月”列(11)中的最后一个值,并迭代到顶部,直到达到值10,并返回该值。

我刚开始在3天前调查VBA并且对语言非常不熟悉所以我仍然试图理解语法。

我毫不怀疑我的想法很模糊,所以我非常感谢我对错误的反馈。

这就是我现在所拥有的:

代码:

Function NextValue(num1 As Range)
For c = num1.End(xlDown) To num1.Item(1)
    If Cells(c, 1) <> num1.End(xlDown) Then
        NextValue = Cells(c, 1)
        Exit For
    End If
Next c
End Function

如果不清楚,这里是逐行描述我正在尝试做的事情。

1)。启动一个从范围结束开始并递减到顶部

的For循环

2)。检查该单元格是否与该列中的最后一个值不匹配

3)。如果没有,则将函数的值设置为该值

4)。终止If语句,For循环,并结束函数。

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

试试这个:

Function NextValue(num1 As Range) as Integer
  Dim y As Integer
    'get the last cell from num1
    Set num1 = num1.End(xlDown)

    y = -1
    Do Until num1.Offset(y, 0).Value <> num1.Value
        y = y - 1
    Loop
    'set function return to the different cell
    NextValue = num1.Offset(y, 0).value
End Function

答案 1 :(得分:1)

这将处理紧凑范围和不相交的范围:

Option Explicit

Public Function SomethingElse(rng As Range) As Variant
    Dim r As Range, values() As Variant
    Dim i As Long, strvalue As Variant
    ReDim values(1 To rng.Count)

    i = 1
    For Each r In rng
        values(i) = r.Value
        i = i + 1
    Next r

    strvalue = values(rng.Count)

    For i = rng.Count To 1 Step -1
        If values(i) <> strvalue Then
            SomethingElse = values(i)
            Exit Function
        End If
    Next i

    SomethingElse = CVErr(xlErrNA)
End Function

enter image description here

答案 2 :(得分:0)

如果您想要在宏

中使用UDF或代码,我不清楚

在第一种情况下,您已经获得了答案

在后一种情况下,您可能需要考虑以下两个选项:

Public Function FirstDifferent(rng As Range) As Variant
    With rng.Parent.UsedRange
        With Intersect(.Resize(, 1).Offset(, .Columns.Count), rng.EntireRow)
            .Value = rng.Value
            .RemoveDuplicates Array(1)
            FirstDifferent = .Cells(.Rows.Count, 1).End(xlUp).Offset(-1).Value
            If FirstDifferent = .Cells(.Rows.Count, 1) Then FirstDifferent = "#N/A"
            .ClearContents
        End With
    End With
End Function

Public Function FirstDifferent(rng As Range) As Variant
    With rng.Resize(, 1)
        .AutoFilter Field:=1, Criteria1:=.Cells(.Rows.Count, 1)
        FirstDifferent = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Cells(1, 1).Offset(-1).Value ' = 0 '<-- if any rows filtered other than headers one then change their column "B" value to zero
        If FirstDifferent = .Cells(.Rows.Count, 1) Then FirstDifferent = "#N/A"
        .Parent.AutoFilterMode = False
    End With
End Function