此问题使用以下数据,这些数据将在固定的单元格范围内手动自适应 - B列范围中的每个单元格都包含公式。它旨在从基础公式单元格中找到最后一个数据单元格。
我想在公式范围B2:B11中找到包含数据的最后一个公式单元格,并从上一个单元格创建一个动态中位数,其上面有四个单元格。中位数应输出到单元格F6 - 结果为9.这是一个动态练习。考虑到下面的代码,有关如何最有效地做到这一点的任何想法?
Sub OutputMedian()
Dim FunctionRange As Range
'Represents a fixed range with function in B2:B11
Set FunctionRange = Worksheets("Sheet1").Range("B2:B11")
'Must start median calc from B9, as it's the last cell with function output data
'Must store Median from last data cell, using 5 cell offset (see output from cell F2)
'Must output the Final (e.g., median output of 9 here) to cell F6
End Sub
答案 0 :(得分:0)
请参阅:Excel VBA: Get Last Cell Containing Data within Selected Range
我通过@brettdj从上面的问题修改了答案(由@varocarbas引用)。谢谢!
搞定了!输出正确的动态中位数,从下面的-4偏移设置五个周期。
Sub OutputMedian()
Dim WS As Worksheet
Dim rng1 As Range
Dim rng2 As Range
Set WS = Sheets("Sheet1")
Set rng1 = WS.Columns("B:B").Find("*", Range("B1"), xlValues, , xlByRows, xlPrevious)
Set rng2 = rng1.Offset(-4, 0)
Dim FirstCell As String
Dim LastCell As String
FirstCell = rng2.Address(0, 0)
LastCell = rng1.Address(0, 0)
Dim CellResponse As String
CellResponse = Evaluate("=median(" & FirstCell & ":" & LastCell & ")")
Range("F6").Value = CellResponse
End Sub
在创建动态函数时使用对象(例如,R1C1,Cells)的更好方法 - 即,不将函数作为连接字符串传递给Evaluate?