[英]How can I make a value in one array the value in another array (VBA)?
I want to create a piece of code that lets me assign a value from a array to another array, which are of different lengths. 我想创建一段代码,使我可以将一个数组中的值分配给另一个长度不同的数组。 This is what I have so far. 到目前为止,这就是我所拥有的。
A(1) = 0
A(2) = 0
A(3) = 6
A(4) = 5
A(5) = 7
n = 0
For i = 1 To 5
If A(i) <> 0 Then
n = n + 1
End If
Next i
ReDim B(1 To n) As Integer
For j = 1 To n
For i = 1 To 5
If A(i) <> 0 Then
B(j) = A(i)
End If
Next i
Next j
MsgBox B(2)
At the moment this returns 7 whereas it should return 5, all values in B are 7. How can I get this code to run? 目前,它返回7,而应返回5,B中的所有值均为7。如何使此代码运行?
The fact that you have nested loops should alarm you: this would be executed n * 5
times, which cannot be correct. 您有嵌套循环的事实应该警告您:这将被执行n * 5
次,这是不正确的。
Change the second part so it only uses one loop, like this: 更改第二部分,使其仅使用一个循环,如下所示:
ReDim B(1 To n) As Integer
j = 1
For i = 1 To UBound(A)
If A(i) <> 0 Then
B(j) = A(i)
j = j + 1
End If
Next i
Note also that using UBound
instead of 5
makes your code more generic. 还要注意,使用UBound
而不是5
会使代码更通用。 Note also that this loop is very similar to the loop that calculates n
. 还要注意,此循环与计算n
的循环非常相似。 The only difference is that you assign to B(j)
. 唯一的区别是您分配给B(j)
。
You could in fact combine it with the first loop, if you would re-dimension B
twice, the second time with Preserve
: 实际上,您可以将它与第一个循环结合起来,如果您要重新命名B
两次,则第二次使用Preserve
:
ReDim B(1 To UBound(A)) As Integer
n = 0
For i = 1 To UBound(A)
If A(i) <> 0 Then
n = n + 1
B(n) = A(i)
End If
Next i
' Shorten the array without losing data:
ReDim Preserve B(1 To n)
You are going to have to check B for the first empty array element and exit the loop so you do not continue to write. 您将必须检查B中的第一个空数组元素并退出循环,因此您无需继续写。
Dim A() As Variant, B() As Variant
Dim i As Long, j As Long, n As Long
A = Array(0, 0, 6, 5, 7) '<~~ 0 to 4, not 1 to 5
n = 0
For i = LBound(A) To UBound(A)
If A(i) <> 0 Then
n = n + 1
End If
Next i
ReDim B(1 To n) '<~~ 1 to 3
For i = LBound(A) To UBound(A)
If A(i) <> 0 Then
For j = LBound(B) To UBound(B)
If IsEmpty(B(j)) Then
B(j) = A(i) '<~~ assigned a value; exit loop
Exit For
End If
Next j
End If
Next i
For j = LBound(B) To UBound(B)
Debug.Print B(j)
Next j
Given that arrays can be either zero-based or one-based, I prefer to use the LBound and UBound functions to define their scope. 鉴于数组可以基于零或基于一,我更喜欢使用LBound和UBound函数来定义它们的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.