遍历一个范围,直到在VBA中find不同的值

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

例:

示例Excel表

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

我刚开始研究VBA 3天前,对这个语言非常不熟悉,所以我仍然试图理解语法。

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

这是我现在所拥有的:

码:

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-Loop

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

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

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

非常感谢您的帮助。

尝试这个:

 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 

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

 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 

在这里输入图像描述

不清楚,如果你想要在macros中使用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