2013-10-19 283 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

@迪克已經夠善於詳細說明這種方法 –