在未知行数的列上执行VBA函数

我试图创build一个函数,各种用户可以执行下面的function,每个用户将有不同数量的行的function,但我不知道如何考虑行数的变化。

Function MKT(ByVal Temperatures As Variant) As Double Dim Sum As Double Dim TemperatureCount As Long Dim GasConst As Double Dim DeltaH As Double Dim Conv As Double Conv = 273.15 GasConst = 8.314472 DeltaH = 10 * GasConst Sum = 0 For TemperatureCount = Temperatures.Cells.Count To 1 Step -1 Sum = Sum + Exp(-DeltaH / (GasConst * (Temperatures(TemperatureCount) + Conv))) Next TemperatureCount MKT = (DeltaH / GasConst) / (-Log(Sum / Temperatures.Cells.Count)) - Conv End Function 

如果将单元格值设置为= MKT(A1:A32557),则函数可以工作,但如果我的值= MKT(A:A),则不能。

我认为这可以帮助,但我不知道如何实现它:

 Dim lastRow As Long lastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row 

另外,是否有可能偏移值1行帐户头?

 lastRowColA = Range("A65536").End(xlUp).Row For Each cell In Range("a2:a" & lastRowColA) 'MsgBox cell Next cell 

或者避免对行限制使用进行硬编码

 with sheet1 lastRowColA = .Range("A" & .Rows.Count).End(xlUp).row Set rng = .range("A2:A" & lastRowColA) end with 

您可以通过与已用范围相交来创build一个温度子集

 Dim SubRange as Range Set SubRange=Intersect(Temperatures,Temperatures.Parent.UsedRange) 

或者如nick和osknows已经发布,您可以使用.End(xlUp),但是请注意,这会忽略隐藏的单元格

 Function SubRange(theRange As Range) As Range Dim LastRow As Long LastRow = theRange.Parent.Cells(theRange.Parent.Rows.Count, theRange.Column).End(xlUp).Row Set SubRange = theRange.Resize(LastRow - theRange.Row + 1) End Function