如何获得连续的最后一个非空单元格的值?

这是一个示例电子表格

示例表

我想select一个范围(例如: A2:E2 )并得到值1 。 如果我selectA4:E4我会得到值1 ; 等等。 有没有办法用macros来实现这一点?

我需要的另一件事是相应列的第一行中的值。 例如:

如果我selectA2:E2我想得到n (因为1在列E中),如果我selectA4:E4我想得到v (因为1在列C中)。

好的,这是一个可以在工作簿中用作公式的函数。 它也解决您的问题。 🙂

将下面的代码粘贴到模块中。

语法/使用

= MyFunc(Cell Range,Arg)

单元格范围 :(必填)范围如A2:E2

Arg :(必需)可以取值为“H”或“R”。 “H”会给你的列标题,“R”会给你的行值

= MyFunc(A1:E2,“H”)会给你“n”AND

= MyFunc(A1:E2,“R”)会给你“1”

 Option Explicit Function MyFunc(rng As Range, stype As String) As Variant Dim MyArray() As String Dim sCol As Long If stype = "" Or (UCase(stype) <> "H" And _ UCase(stype) <> "R") Then Exit Function With rng MyArray = Split(.Address, "$") sCol = Cells(Val(MyArray(UBound(MyArray))), _ Columns.Count).End(xlToLeft).Column If UCase(stype) = "H" Then MyFunc = Cells(1, sCol) ElseIf UCase(stype) = "R" Then MyFunc = Range(MyArray(UBound(MyArray) - 1) & _ MyArray(UBound(MyArray))).Value End If End With End Function 

注意:这只是一个通用的代码,告诉你它是如何工作的,而且目前还不能处理任何错误。

下面的代码应该做你想要的。 注意:我没有select任何东西,因为这会让事情变得没有任何好处。

 Dim ColLast as Long Dim ValueColLast as String Dim HeadColLast as String With Sheets(xxxxx) ColLast = .Cells(2,Columns.Count).End(xlToLeft).Column ValueColLast = .Cells(2, ColLast).Value HeadColLast = .Cells(1,ColLast).Value End With 

Cells(Row, Column)地址由活动工作表中的行和列标识的单元格。 行必须是一个数字。 列可以是数字(例如1或104)或列标识符(例如“A”或“CZ”)

.Cells(Row, Column)地址由With语句中标识的工作表.Cells(Row, Column)和列标识的单元格。 注意领先点。

.Cells(2,Columns.Count)解决了第2行中的最后一个单元格,因为Columns.Count给出了当前版本Excel的每个工作表的列数。 `Rows.Count对行也是一样的。

假设.Cells(2,Columns.Count)是空白的.Cells(2,Columns.Count).End(xlToLeft)find指定方向上的下一个单元格的值。 这是Ctrl + LeftArrow的VBA等价物。 xlToRightxlUpxlDown允许您在其他方向上移动。 .Cells(Rows.Count,"A").End(xlUp)给出列A中最后使用的行。

.Cells(2,Columns.Count).End(xlToLeft).Column给出了第2行中最后使用的列的编号。

ValueColLast = .Cells(2, ColLast).Value将ValueColLast设置为第2行最后一个单元格的值。我将ValueColLast定义为一个string,因为如果我认为它是一个数字并将其定义为Long,则会得到错误,如果不是。

HeadColLast = .Cells(1,ColLast).Value将HeadColLast设置为行1中的值。

希望这一切都有道理。