VBA 数组重复
VBA Array repetition
我正在尝试制作一个接受 3 个值的函数,并以数组格式输出三个不同数字中的许多(在本例中为 1、2、4)。例如:EntryArray(1,2,1) 将垂直输出:1,1,2,2,2,4,4。但是,它应该重复这个数组一定次数(作为最后一个值给出),这部分我无法开始工作。例如:EntryArray(2,1,1,4) 应该给出:
1,1,2,4,1,1,2,4,1,1,2,4,1,1,2,4
我的代码如下:
Function EntryArray(One As Integer, Two As Integer, Four As Integer, Rept As Integer) As Integer()
Dim Length As Integer
Length = One + Two + Four
Dim entry() As Integer
ReDim entry(0 To Length, 0)
For i = 1 To Length
entry(i, 0) = 1
If i > One Then entry(i, 0) = 2
If i > Two + One Then entry(i, 0) = 4
Next i
EntryArray = entry
End Function
简单地创建进入1、2、4的循环并循环Rept次。使用单独的计数器来跟踪将值插入 entry
的位置
我简化了插入 1、2、4 的逻辑并切换为 Long 类型。使用 Integer
没有任何优势
此外,您还有一些“差一个”的问题。使用基于 1 的数组更容易
Function EntryArray(One As Long, Two As Long, Four As Long, Rept As Long) As Long()
Dim i As Long, j As Long, n As Long
Dim Length As Long
Length = One + Two + Four
Dim entry() As Long
ReDim entry(1 To Length * Rept, 1 To 1)
n = 1
For j = 1 to Rept
For i = 1 To One
entry(n, 1) = 1
n= n + 1
Next
For i = 1 To Two
entry(n, 1) = 2
n= n + 1
Next
For i = 1 To Four
entry(n, 1) = 4
n= n + 1
Next
Next
EntryArray = entry
End Function
我正在尝试制作一个接受 3 个值的函数,并以数组格式输出三个不同数字中的许多(在本例中为 1、2、4)。例如:EntryArray(1,2,1) 将垂直输出:1,1,2,2,2,4,4。但是,它应该重复这个数组一定次数(作为最后一个值给出),这部分我无法开始工作。例如:EntryArray(2,1,1,4) 应该给出: 1,1,2,4,1,1,2,4,1,1,2,4,1,1,2,4
我的代码如下:
Function EntryArray(One As Integer, Two As Integer, Four As Integer, Rept As Integer) As Integer()
Dim Length As Integer
Length = One + Two + Four
Dim entry() As Integer
ReDim entry(0 To Length, 0)
For i = 1 To Length
entry(i, 0) = 1
If i > One Then entry(i, 0) = 2
If i > Two + One Then entry(i, 0) = 4
Next i
EntryArray = entry
End Function
简单地创建进入1、2、4的循环并循环Rept次。使用单独的计数器来跟踪将值插入 entry
我简化了插入 1、2、4 的逻辑并切换为 Long 类型。使用 Integer
没有任何优势此外,您还有一些“差一个”的问题。使用基于 1 的数组更容易
Function EntryArray(One As Long, Two As Long, Four As Long, Rept As Long) As Long()
Dim i As Long, j As Long, n As Long
Dim Length As Long
Length = One + Two + Four
Dim entry() As Long
ReDim entry(1 To Length * Rept, 1 To 1)
n = 1
For j = 1 to Rept
For i = 1 To One
entry(n, 1) = 1
n= n + 1
Next
For i = 1 To Two
entry(n, 1) = 2
n= n + 1
Next
For i = 1 To Four
entry(n, 1) = 4
n= n + 1
Next
Next
EntryArray = entry
End Function