我遇到了数组边界的问题。我有3个工作表。前2个我转换成两个数组(array1& array2),然后在它们之间进行计算以创建第三个。问题是我不确定第三个数组的边界是什么,因为它总是会根据输入而改变
我一直在使用 Dim array3(5000,5),假人有5000行(第一维)因为我认为不会有更多。有没有办法创建没有边界的数组,然后添加信息,然后调暗尺寸?
我创建的宏也使用了这段代码---
Z = 1
For x = 1 To UBound(array1, 1)
For y = 1 To UBound(array2, 1)
If array1(x, 4) = 0 Then
GoTo Line1
End If
If array1(x, 1) = array2(y, 1) And array1(x, 2) = array2(y, 3)Then
If array1(x, 4) > array2(y, 5) Then
array3(z, 1) = array1(x, 3)
ElseIf array1(x, 4) = array2(y, 5) Or array1(x, 4) < array2(y, 5) Then
array3(z, 1) = array1(x, 3)
End If
z = z + 1
End If
Next y
Line1:
Next x
它需要一个array1并通过array2循环它并在array3中创建一个结果
基本上当array1(x,4)= 0时,我需要它继续下一个X.我无法弄清楚如何在没有GoTO Line1的情况下循环它。如果我将其向下移动,那么它将继续循环通过arry2(y),而不是继续前进到下一个X.如果我将其移动到上方,则y重置并且它再次通过For y循环
答案 0 :(得分:1)
喜欢这个(注释)代码:
Dim x As Long, y As Long, z As Long
Dim array1 As Variant, array2 As Variant
array1 = ... ' your way of filling array1
array2 = ... ' your way of filling array2
ReDim array3(LBound(array1, 1) To UBound(array1, 1) * UBound(array2, 1), LBound(array1, 1) To LBound(array1, 2) ' dim Array 3 to the theoretically maximum number of rows and to the wanted columns number (here, the same as array1 columns
z = LBound(array3, 1) - 1 'start from array3 rows number lower bound minus one to update at every matching criteria
For x = LBound(array1, 1) To UBound(array1, 1)
For y = LBound(array2, 1) To UBound(array2, 1)
If array1(x, 4) <> 0 Then
If array1(x, 1) = array2(y, 1) And array1(x, 2) = array2(y, 3) Then
z = z + 1
If array1(x, 4) > array2(y, 5) Then
array3(z, 1) = array1(x, 3)
Else
array3(z, 1) = array2(x, 3) ' see my guess here instead of your original code
End If
End If
End If
Next
Next
If z >= 0 Then
array3 = Application.Transpose(array3) 'transpose array3
ReDim Preserve array3(LBound(array1, 1) To LBound(array1, 1) + 1, LBound(array1, 1) To z) 'redim its columns to their actually filled number, while preserving values
array3 = Application.Transpose(array3) 'trasnpose back your array3
End If
答案 1 :(得分:0)
是的,你可以!有多种方法可以达到这个目标!
您可以轻松地使用Redim保留阵列。试着看:
https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/redim-statement
请记住,您只能使用此方法重新生成数组的最后一个维度。如果您需要更改其他人,则需要了解如何更改阵列以执行此操作。 HEre是另一个很棒的链接
ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6
您还可以在处理之前获取前两张纸的行数和列数。这样,您可以稍后使用此信息。
试试这个:
THisworkbook.sheets("sheet1").USedRange.rows.count
THisworkbook.sheets("sheet1").USedRange.columns.count