添加到所有其他阵列位置MS Access

时间:2018-07-03 14:20:24

标签: vba ms-access

我需要一个数组(firstArray)并输入到第二个数组(secondArray)。但是,前四个字段的值相同。在前四个位置之后,它开始交替显示值。

示例:

firstArray

+---------+
| ID#     |
| Name    |
| month1  |
| month2  |
| month3  |
| etc...  |
+---------+

secondArray

+----------+
| ID#      |
| Name     |
| month1   |
| month2   |
| NewField |
| month3   |
| NewField |
| month4   |
| etc...   |
+----------+

我对VBA还是很陌生,所以对糟糕的代码表示歉意。

到目前为止的代码:

Dim i As Integer
i = 0
Dim j As Integer
ReDim secondArray(0 To (fieldCount - 4) * 2)
Dim finalCountDown As Integer
finalCountDown = (fieldCount - 4) * 2

secondArray(0) = firstArray(0)
secondArray(1) = firstArray(1)
secondArray(2) = firstArray(2)
secondArray(3) = firstArray(3)

i = 3
j = 3
Do Until i > finalCountDown
    i = i + 1
    secondArray(i) = "NewField"
    i = i + 1
    j = j + 1
    secondArray(i) = firstArray(j)
Loop

我还有一个MsgBox可以迭代并输出我的字段:

'//------ testing output
i = 0
For i = 0 To finalCountDown
    MsgBox secondArray(i)
Next i

感谢您的帮助!如果有任何混淆,我将很乐意尝试解释更多内容!

编辑:

两个数组的大小不同,但是是动态的。首先将firstArray设置为20位置,然后将firstArray最初设置为32位置。 (这些是在每次运行该过程并提取存档数据时计算出来的。这使我的用户可以添加数据,而不必担心必须手动将值添加到我的数组中。)

EDIT2:

我在代码中添加了Erik的部分,并做了一些改动。我还为firstArray添加了一个单独的计数器,以确保将正确的行输入到secondArray的正确位置。

EDIT3:

下面是对我有用的代码:

Dim i As Integer
i = 0
Dim j As Integer
'removed the " - 4"
ReDim secondArray(0 To (fieldCount * 2))
Dim finalCountDown As Integer
'removed the " - 4"
finalCountDown = (fieldCount * 2)

secondArray(0) = firstArray(0)
secondArray(1) = firstArray(1)
secondArray(2) = firstArray(2)
secondArray(3) = firstArray(3)

i = 3
'created own counter for firstArray
j = 3
Do Until i > finalCountDown
    i = i + 1
    secondArray(i) = "NewField"
    i = i + 1
    j = j + 1
    secondArray(i) = firstArray(j)
Loop

我遇到的错误是由于“ {下标不在范围内”而引起的,原因是我的finalCountDown变量小于需要的数组。允许变量变得比我的数组大,这允许我的数组完成自身的迭代,现在以正确的顺序输入适当的字段。

我接受Erik的回答,因为这是回答问题的垫脚石!

1 个答案:

答案 0 :(得分:1)

对于调整后的代码,您可以进行简单检查以检查j值是否有效:

Dim i As Integer
i = 0
Dim j As Integer
ReDim secondArray(0 To (fieldCount - 4) * 2)
Dim finalCountDown As Integer
finalCountDown = (fieldCount - 4) * 2

secondArray(0) = firstArray(0)
secondArray(1) = firstArray(1)
secondArray(2) = firstArray(2)
secondArray(3) = firstArray(3)

i = 3
j = 3
Do Until i > finalCountDown
    i = i + 1
    finalArray(i) = "NewField"
    i = i + 1
    j = j + 1
    If j => LBound(colheaders) And j <= UBound(colHeaders) Then
        finalArray(i) = colHeaders(j)
    End If
Loop