对具有未知行数的列执行VBA函数

时间:2011-06-06 16:25:28

标签: excel vba

我正在尝试创建一个函数,各个用户可以在一个列上执行下面的功能,每个用户都有不同的行数,但我无法弄清楚如何允许数量的变化行。

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行以考虑标题?

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

或避免硬编码行限制使用

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

答案 2 :(得分:1)

您可以通过与使用范围

交叉来创建温度子集
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