0

我正在使用 VBA 计算成对斜率,将它们存储在一个数组中,然后使用 Chip Pearson 在工作表上转置数组的技术对它们进行排序。当斜率数超过 65K 时,我的代码将失败,这在 Excel 2003 中是有意义的,因为行数。我认为它可以在 Excel 2010 中工作,但我似乎有同样的问题。有谁知道 Resize 属性或 Transpose 方法是否有限制?

谢谢

Sub pairwise()
Dim endrow As Long, i As Long, j As Long, s As Long
Dim num As Double, denom As Double, sij As Double
Dim r As Range
Dim slopes()

endrow = Range("A1").End(xlDown).Row
n = endrow - 1
nrd = endrow * n / 2
ReDim slopes(nrd)
Debug.Print LBound(slopes); UBound(slopes)
For i = 1 To n
For j = (i + 1) To endrow
    num = Cells(i, 2).Value - Cells(j, 2).Value
    denom = Cells(i, 1).Value - Cells(j, 1).Value
    If denom <> 0 Then
        sij = num / denom
        slopes(s) = sij
        s = s + 1
    End If
Next j
Next i

Set r = Range("C1").Resize(UBound(slopes) - LBound(slopes) + 1, 1)
    r = Application.Transpose(slopes)

    ' sort the range
    r.Sort key1:=r, order1:=xlAscending, MatchCase:=False
End Sub
4

2 回答 2

1

这是该Transpose方法的限制。

我的建议是从一开始就将您的数组声明为 2D

Redim Slopes(1 To nrd, 1 To 1)

此外,您应该使用 Variant Array 方法,而不是循环遍历循环中的单元For

于 2013-10-19T03:00:09.643 回答
1

我在 INDEX 函数上发现了同样的限制。http://dailydoseofexcel.com/archives/2013/10/11/worksheetfunction-index-limitations/

以下是如何使输出数组成为二维数组并一次读取所有值,而不是在循环中读取。

Sub pairwise()

    Dim lEndRow As Long
    Dim vaValues As Variant
    Dim aSlopes() As Variant
    Dim lCnt As Long
    Dim rOutput As Range
    Dim i As Long, j As Long

    'A 2d array here can easily be written to a sheet
    lEndRow = Sheet3.Range("a1").End(xlDown).Row
    ReDim aSlopes(1 To lEndRow * (lEndRow - 1), 1 To 1)

    'Create a two-d array of all the values
    vaValues = Sheet3.Range("A1").Resize(lEndRow, 2).Value

    'Loop through the array rather than the cells
    For i = LBound(vaValues, 1) To UBound(vaValues, 1) - 1
        For j = 1 + 1 To UBound(vaValues, 1)
            If vaValues(i, 1) <> vaValues(j, 1) Then
                lCnt = lCnt + 1
                aSlopes(lCnt, 1) = (vaValues(i, 2) - vaValues(j, 2)) / (vaValues(i, 1) - vaValues(j, 1))
            End If
        Next j
    Next i

    'Output the array to a range, and sort
    Set rOutput = Sheet3.Range("C1").Resize(UBound(aSlopes, 1), UBound(aSlopes, 2))
    rOutput.Value = aSlopes
    rOutput.Sort rOutput.Cells(1), xlAscending, , , , , , , , False

End Sub
于 2013-10-19T14:25:19.463 回答