VBA t_test 和本机 excel t_test 之间的不同结果

different results between VBA t_test and native excel t_test

这是我第一次涉足 VBA。以下子例程计算 Sheet1 上两列数据的 t 检验。

问题是这个子例程 returns 的值与我手动获得的值不同 运行 "=T.TEST(A1:A41,B1:B96, 2,3)”,比如说,工作表上的单元格 D1。 (table 中的数字并不重要。我已经用真实数据以及 A1:A41 列中的 1 到 41 和 B1:B96 列中的 1 到 96 进行了测试。)你确认了吗?代码中有错误吗?谢谢。

Sub dummy_ttest()
    Dim rng0 As Range
    Dim rng1 As Range

    Set rng0 = Sheets("Sheet1").Range("A1:A41")
    Set rng1 = Sheets("Sheet1").Range("B1:B96")

    Dim td0() As Double
    Dim td1() As Double
    
    ReDim td0(rng0.Count) As Double
    ReDim td1(rng1.Count) As Double

    Dim i As Integer
    Dim v As Variant

    'copy rng0 to td0
    i = 0
    For Each v In rng0
       td0(i) = v.value
       i = i + 1
    Next v

    'copy rng1 to td1
    i = 0
    For Each v In rng1
       td1(i) = v.value
       i = i + 1
    Next v

    Dim myttest As Double
    myttest = Application.WorksheetFunction.T_Test(td0, td1, 2, 3)

    MsgBox myttest

End Sub

使用变体数组并批量加载它们:

Sub dummy_ttest()
    Dim rng0 As Range
    Dim rng1 As Range

    Set rng0 = Sheets("Sheet1").Range("A1:A41")
    Set rng1 = Sheets("Sheet1").Range("B1:B96")

    Dim td0() As Variant
    Dim td1() As Variant
    
    td0 = rng0.Value
    td1 = rng1.Value

    Dim myttest As Double
    myttest = Application.WorksheetFunction.T_Test(td0, td1, 2, 3)

    MsgBox myttest

End Sub

斯科特有一个很好的答案,但添加了上下文/将我的评论转换为答案:

One thing I can see is that your arrays are one element bigger than your ranges

The issue is that your arrays are 0-based, but the range is one-based. Your array is equivalent to ReDim td0(0 to rng0.Count) As Double, but the range has 1 to rng0.Count cells. It's not an issue of ReDim at all.

范围A1:A41有41个单元格,但你的数组有42个元素; 0 to 41 表示你有太多了。因此,在您当前的方法中,您实际上从未填充数组的最后一个元素,因此默认情况下它是 0

您可以(并且应该)指定数组的下限,即

ReDim td0(0 to rng0.Count - 1) As Double '<~ 0-based

ReDim td0(1 to rng0.Count) As Double '<~ 1-based

来自 ReDim 文档:

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.