我有以下代码,它基于它应该工作的逻辑。
我希望它是(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
有什么想法吗?
答案 0 :(得分:3)
没有临时数组的可能性是:
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
答案 1 :(得分: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
答案 2 :(得分:1)
当你执行t(k)= t(a - k)时,将t(a-k)分配给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
请注意,您只需要迭代多次,即数组大小的一半(向下舍入),否则您将再次交换值,并最终得到相同的起始数组。