2017-05-28 68 views
2

我有以下代碼,它基於它應該工作的邏輯。在Excel中反轉數組VBA

我想這是(4,3,2,1),但在循環結束時,我得到T =(4,3,3,4)

Sub try() 

    Dim t As Variant 

    t = Array(1, 2, 3, 4) 
    a = UBound(t) 

    For k = 0 To a 
    t(k) = t(a - k) 
    Next k 

End Sub 

任何想法?

回答

2

您必須使用臨時數組來存儲這些東西,然後再進行切換,否則它將被覆蓋。

這是你正在嘗試?

Sub try() 
    Dim t As Variant, tmpAr As Variant 
    Dim a As Long, b As Long, i As Long 

    t = Array(1, 2, 3, 4) 

    a = UBound(t): b = LBound(t) 

    For i = 0 To ((a - b) \ 2) 
     tmpAr = t(i) 
     t(i) = t(a) 
     t(a) = tmpAr 
     a = a - 1 
    Next i 

    For i = 0 To UBound(t) 
     Debug.Print t(i) 
    Next i 
End Sub 

![enter image description here

+1

[email protected]:D固定!謝謝。猜猜我變老了 –

2

做到這一點而不臨時數組A可能性是:

  • Join用定界符例如陣列逗號
  • StrReverse生成的字符串
  • Split對原有的分隔符

代碼反轉字符串:

Option Explicit 

Sub try() 

    Dim t As Variant 
    Dim i As Long 

    t = Array(1, 2, 3, 4) 
    t = Split(StrReverse(Join(t, ",")), ",") 

    For i = 0 To UBound(t) 
     Debug.Print t(i) 
    Next i 

End Sub 

輸出:

4 
3 
2 
1 
+0

光滑而美麗。 –

1

當你做T(K )= t(a - k)您將t(ak)分配給t(k),但是存儲值在t(k)中丟失。你需要暫時存儲在另一個變量(在下面的例子中變量x),那麼你就可以T(K)和T之間交換的價值 - 這樣的(A K):

Sub try() 

    Dim t As Variant 
    Dim x As Variant 
    Dim b As Integer 

    t = Array(1, 2, 3, 4) 
    a = UBound(t) 
    b = (a - 1)/2 

    For k = 0 To b 
    x = t(k) 
    t(k) = t(a - k) 
    t(a - k) = x 
    Next k 

End Sub 

請注意,您只需要迭代多次,這是你的數組大小的一半(向下取整),否則你會再次交換值,並且會以相同的起始數組結束。