情况:
我有一个名为arrayPartNo的二维数组,其大小为2维(1,X)。它在第二维中包含的每个X记录都是包含0,7,15,23等(所以+8)个字符的字符串。
为了便于理解,它包含未知数量的部件号,每个部件号的长度为7个字符。我有多个部件号,它们用分号分隔(原因为+ 8而不是+7)。
目标:
创建另一个名为GoodArray的二维数组,其大小为第一维X(与上面相同),在第二维中我想分别存储每个零件编号。
举个例子,如果arrayPartNo的记录Y包含3个Part Number(所以它的长度为3 * 7 + 2 * 1 = 23),我想将这3个值存储在GoodArray(Y,0)中GoodArray(Y,1)和GoodArray(Y,2)。
这就是我在下面的代码中所做的,但是GoodArray的动态声明在Do While循环开始时产生了一个问题。
问题:
有关如何解决该问题的任何想法?
'Dim arrayPartNo() As Variant
'... : Part where I store values in the arrayPartNo
Dim NumberOfPartNo As Integer ' Number of PartNo in a specific row
Dim length As Integer ' length of a correct PartNo
Dim GoodArray() As Variant
For i = 0 To UBound(arrayPartNo, 2)
length = 7
NumberOfPartNo = 0
Do
GoodArray(i, NumberOfPartNo) = Mid(arrayPartNo(0, i), length + 1 - 7, 7)
NumberOfPartNo = NumberOfPartNo + 1
length = length + 8
Debug.Print GoodArray(i, NumberOfPartNo)
Loop While Len(arrayPartNo(0, i)) >= length
Next i
答案 0 :(得分:0)
解决方案:
我基本上找到了一种方法来应用我并不熟悉的Redim Preserve
方法。
以下代码有效:
'1) First part, I calculate the size of the 2nd dimension of GoodArray() (which I will declare later), this size is the biggest number of PartNo contained in a record of arrayPartNo
Dim h As Integer
Dim longest As Integer
longest = 0
For h = 0 To UBound(arrayPartNo, 2)
If Len(arrayPartNo(0, h)) > longest Then longest = Len(arrayPartNo(0, h))
Next h
'MsgBox longest '63 in my case
h = (longest + 1) / 8 ' since h was only used in the loop above we reuse it to store this = 8 in my case -> size of the 2nd dimension
longest = UBound(arrayPartNo, 2) ' same here, we just reuse the variable to store this -> size of the 1st dimension (588 in my case)
Dim NumberOfPartNo As Integer ' Number of PartNo in a specific row
Dim length As Integer ' length of a correct PartNo
Dim GoodArray() As Variant
ReDim Preserve GoodArray(longest, h)
For i = 0 To UBound(arrayPartNo, 2)
length = 7
NumberOfPartNo = 0
If Len(arrayPartNo(0, i)) > 0 Then
Do
GoodArray(i, NumberOfPartNo) = Mid(arrayPartNo(0, i), length + 1 - 7, 7)
Debug.Print GoodArray(i, NumberOfPartNo) & " " & i
NumberOfPartNo = NumberOfPartNo + 1
length = length + 8
Loop While Len(arrayPartNo(0, i)) >= length
End If
Next i