我有一个 2D 数组类型Variant
。填充数组的大小和值是根据工作表中的数据生成的。该数组需要进一步处理,主要是几个值的插值。我正在用这个插值函数 http://www.ozgrid.com/forum/showthread.php?t=64100(我知道 Excel 等效函数,但设计选择不使用它们)。我遇到的问题是 Interpolation 函数需要 Range 对象。
我已经尝试修改函数以使用变体(r as Variant
) 争论。下面一行nR = r.Rows.Count
可以替换为nR = Ubound(r)
。虽然这有效,但我也想在任何工作表中正常使用此函数,并且不以任何方式更改该函数。
Sub DTOP()
Dim term_ref() As Variant
' snip '
ReDim term_ref(1 To zeroRange.count, 1 To 2)
' values added to term_ref '
' need to interpolate x1 for calculated y1 '
x1 = Common.Linterp(term_ref, y1)
End Sub
插值函数
Function Linterp(r As Range, x As Double) As Double
Dim lR As Long, l1 As Long, l2 As Long
Dim nR As Long
nR = r.Rows.Count
' snipped for brevity '
End Function
如何将内存中的变体数组转换为 Range 以便将其用于插值函数? (不输出到工作表)
Answer
简而言之,答案是你不能。 Range 对象必须引用工作表。
更改后的插值函数检查TypeName
的参数并设置值nR
因此。不是最漂亮的解决方案。
作为注释,VarType
事实证明,函数在这种情况下毫无用处,因为VarType(Variant())
and VarType(Range)
返回相同的值(即 vbArray)并且无法用于消除数组与范围的歧义
Function Linterp(r As Variant, x As Variant) As Double
Dim lR As Long, l1 As Long, l2 As Long
Dim nR As Long
Dim inputType As String
inputType = TypeName(r)
' Update based on comment from jtolle
If TypeOf r Is Range Then
nR = r.Rows.Count
Else
nR = UBound(r) - LBound(r) 'r.Rows.Count
End If
' ....
End Function