有没有办法将所有值从一个数组转移到另一个数组,然后擦除原始数组



我在工作中试图开发的一块代码遇到了问题。从本质上讲,我正在excel中创建一个用户表单,当轨道车在某个位置装载时,人们会在其中输入数据(我们称之为"点1、点2、点3等"(

有时他们不得不把车移到另一个地方,在这种情况下,我希望他们能够保留第一个/原始条目中轨道车上的所有信息,然后在完成后从原始位置删除数据。

为了以更精简的方式实现这一点,我为5个点中的每一个建立了数组,这些点引用了他们在用户表单上输入数据的所有单元格:

Dim spot1information(14)
spot1information(0) = UserForm.ProductType1.Value
spot1information(1) = UserForm.ProductID1.Value
spot1information(2) = UserForm.BatchID1.Value
etc....
Dim spot2information(14)
spot2information(0) = UserForm.ProductType2.Value
spot2information(1) = UserForm.ProductID2.Value
spot2information(2) = UserForm.BatchID2.Value
etc....

所有五个位置依此类推。我不知道这是否会让事情变得更困难,但请注意,这些数组值并不都是同一类型的。例如,索引(0(将是一个字符串,但索引(10(是一个DATETIME,索引(12(被定义为Long。

假设他们正在将一辆汽车从地点1移到地点2。简而言之,我想让代码做以下事情:

  • 将spot2information(当前为空(中的索引0-6的值替换为spot1information(用户已在用户表单上填写(中的索引号0-6
  • 我只对指数0-6感兴趣,因为它们包含相关的轨道车信息
  • 将spot1信息的每个值清空为"0">

为了实现这一点,我尝试了以下代码及其一些变体:

If OriginalSpot.Value = 1 Then
If DestinationSpot.Value = 2 Then
For i = 0 to 6
spot2information(i) = spot1information(i)
Next
For Each i in spot1information
spot1information(i) = ""
Next
End If
End If

然而,这不断出现类型不匹配的问题。我之所以这么想,是因为spot2information数组中的数据是空的,而spot1information阵列中的数据不是,但我不完全确定如何解决这一问题。


更新:我执行了下面的建议,并将spot1information(i) = ""替换为Erase spot1information

代码现在基本上可以工作了!数组"的值;spot2formation";现在是";spot1formation";,用";spot1formation";现在是空的。

下面建议的2D阵列也很有魅力。我一直面临的新问题是数组值正在更新,但userform没有。(注意:以后我会把这类事情作为一个单独的问题发布,我很抱歉!(

更容易将其作为2D阵列进行管理:

Sub Tester()
Dim spots(1 To 5, 0 To 14), n As Long, i As Long

'fill your spot arrays from the form....
For n = 1 To 5
spots(n, 0) = UserForm.Controls("ProductType" & n).Value
spots(n, 1) = UserForm.Controls("ProductID" & n).Value
spots(n, 2) = UserForm.Controls("BatchID" & n).Value
'etc etc
Next n

'swap a spot with another
Debug.Print spots(2, 1), spots(3, 1)
SwapSpots spots:=spots, fromSpot:=2, toSpot:=3
Debug.Print spots(2, 1), spots(3, 1)
End Sub

Sub SwapSpots(spots, fromSpot As Long, toSpot As Long)
Dim n As Long
For n = 0 To 6
spots(toSpot, n) = spots(fromSpot, n)
spots(fromSpot, n) = Empty 'empty the source slot value
Next n
End Sub

假设阵列的DataTypeIndex相同,即index(0)对所有点都是stringIndex(2)对所有点是long,依此类推

如果是这样的话,那么这个部分不应该产生任何错误:

For i = 0 to 6
spot2information(i) = spot1information(i)
Next

错误应该更准确地发生在标有#的行中

For Each i in spot1information
spot1information(i) = ""   '#
Next

错误的原因似乎是试图将字符串值""分配给给定"的数字类型;不匹配">错误。

使用CCD_ 10表示您想要";启动">或擦除整个数组,因此我建议使用这一行而不是For…Next方法。

Erase spot1information

关于此:

但我现在遇到了一个新问题,用户表单上的值没有更新以反映存储在数组中的新值。我需要以某种方式";刷新";用户表单?

您刚刚更新了数组,然后需要运行用于更新UserForm中受两个数组影响的对象的值的过程。

最新更新