您应该检测是否支持 .Formula2,如果支持,则使用 .Formula2,否则使用 .Formula
这就是您确定Excel版本是否支持DA函数的方法。它没有说的是,您可以通过尝试分配给该属性来在不支持 DA 函数的系统上捕获错误 1004。
所以我们可以想象封装一个检查来看看是否Formula2
被支持,作为一个属性ThisWorkbook
module:
Private SupportsDA As Boolean
Public Property Get SupportsDynamicArrays() As Boolean
Static BeenThere As Boolean
If Not BeenThere Then ' only do this once
Dim LateBoundCell As Object
Set LateBoundCell = Application.ActiveCell
If LateBoundCell Is Nothing Then
'if there is no active sheet/cell, we cannot tell
SupportsDA = False ' err on the safer side
BeenThere = False ' better luck next time, maybe
Else
BeenThere = True
On Error Resume Next
LateBoundCell.Formula2 = LateBoundCell.Formula2
If Err.Number = 438 Then
'Range.Formula2 is inexistent, return false.
SupportsDA = False
ElseIf Err.Number = 1004 Then
'DA not supported
SupportsDA = False
Else
SupportsDA = True
End If
On Error GoTo 0
End If
End If
SupportsDynamicArrays = SupportsDA
End Property
我想我会用一个结束通话Sub
过程需要一个Object
后期绑定参数Range
,以及公式字符串 - 像这样:
Public Sub SetFormula(ByVal Target As Object, ByVal Formula As String)
If Not TypeOf Target Is Range Then Err.Raise 5 ' invalid argument
If ThisWorkbook.SupportsDynamicArrays Then
Target.Formula2 = Formula ' late-bound call will still compile in older hosts
Else
Target.Formula = Formula
End If
Else
End If
这样其余的代码就可以完成SetFormula someCell, someFormula
无需担心这是否会发生Formula2
or Formula
,但他们仍然可以检查是否ThisWorkbook.SupportsDynamicArrays
有条件地确定要通过什么公式......如果遇到更好的方法,那么就留下了一个可以调整的地方!