获取距离当前值最近的单元格

在主要由空白单元格填充的列中,我需要获取最接近当前选定单元格的单元格的值,并且不是空白的。

虽然“不是空白”的部分可以通过IFISBLANK声明很容易地实现,但是我不知道如何从当前的空白处获得第一个单元的位置。

Excel工作表

在这个示例电子表格的单元格C7中,我想显示B7的值减去B4的值( = B7-B4 )。 问题是这些值由不可预知数量的单元格分隔,范围从0到20甚至更多。 需要parsing一个包含数千行和频繁数据的电子表格,手动select上面的单元格不是一个选项。

继续我的例子,我想C13显示= B13-B10 ,但让我们说,他们之间还有两个空行(第13行成为第15行),我希望它显示= B15 – B10

可以通过MATCH查询获取该位置,知道types将始终为T1或T2?

先谢谢你。

C2单元格中input此公式并将其拖动到底部。

=IFERROR(IF(B2="","",B2-LOOKUP(9.99999999999999E+307,B$1:B1)),"")

在这里输入图像说明

通过VBA编写公式

下面你会发现一个VBA的方法,将你的减法公式写到C列中。 顺便说一句,通过数组search比在一个范围内循环要快得多。

 Option Explicit Sub subtractLastValueRow() ' declare vars Dim oSht As Worksheet ' work sheet Dim a As Variant ' one based 2-dim data field array Dim n As Long ' last row in column B Dim i As Long ' item no Dim ii As Long ' last item no Dim j As Long Dim s As String ' set sheet Set oSht = ThisWorkbook.Worksheets("MySheet") ' fully qualified reference to worksheet ' get last row number of search column n = oSht.Range("B" & oSht.Rows.Count).End(xlUp).Row If n < 2 Then Exit Sub ' only if data avaible (row 1 = title line) ' get range (after title line) values to one based 2dim data field array a = oSht.Range("B2:C" & n).Value ' array gets data from eg "A2:A100" ' loop through column B to find keyword sKey If Len(a(1, 1) & "") > 0 Then ii = 1 + 1 ' first item in array For i = LBound(a) + 1 To UBound(a) ' array boundaries counting from 1+1 to n -1 (one off for title line) ' value found If Len(a(i, 1) & "") > 0 Then For j = i + 1 To UBound(a) If Len(a(j, 1) & "") > 0 Then ' write .Formula (alternatively use .Value, if value wanted) oSht.Range("C" & i + 1).Formula = "=B" & i + 1 & "-B" & ii ii = i + 1 ' note last found i Exit For End If Next j End If Next If Len(a(UBound(a), 1) & "") > 0 Then ' last item in array oSht.Range("C" & UBound(a) + 1).Formula = "=B" & UBound(a) + 1 & "-B" & ii End If End Sub 

注意

如果您想要写入值而不是工作表公式 ,只需将.Formulareplace为.Value

在C3单元格中input以下公式:

=B3-LOOKUP(2,1/$B$1:B2,$B$1:B2)

并根据需要复制到所有T2单元格中。