2013-10-19 241 views
0

我使用VBA来计算成对的山坡,将它们存储在一个数组,然后用换位上workheet阵列对它们进行排序的芯片Pearson的技术。我的代码在斜率数超过65K时失败,这在Excel 2003中是有意义的,这是由于行数。我认为它会在Excel 2010中工作,但我似乎有同样的问题。有谁知道Resize属性或Transpose方法是否存在限制?Excel VBA范围调整大小限制?

由于

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 

回答

0

我发现同样的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 
+0

非常酷。快速注,使用ReDim线应'使用ReDim aSlopes(1至lEndRow *(lEndRow-1)/ 2,1至1)' –

+0

并且,通过阵列循环花费约45%的时间与通过细胞循环( 0.60秒与1.33秒),计算和分类65,341斜坡:) –

+0

这就是我原来的ReDim,但是我跑出阵列的房间。我知道你会弄清楚细节。 :) –

1

它的Transpose方法的限制。

我的建议是从一开始就

Redim Slopes(1 To nrd, 1 To 1) 

还声明您的数组为2D,您应该使用的,而不是在你的For循环遍历细胞中的变量数组方式

+0

的感谢!所以当我使用二维数组时,代码会变成'r =斜坡'?你能否详细介绍一下Variant数组方法? –

+0

@迪克已经够善于详细说明这种方法 –