【发布时间】:2022-01-11 04:31:14
【问题描述】:
我有以下代码可以完美运行并完成我需要的技巧。
但是我希望这段代码运行 n 次并创建 n 个数组。
我的数据集是:
我的代码是:
Option Explicit
Private Sub Test()
Const startRow As Long = 2
Const valueCol As Long = 2
Const outputCol As Long = 4
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, valueCol).End(xlUp).Row
Dim inputArr As Variant
inputArr = ws.Range(ws.Cells(startRow, valueCol), ws.Cells(lastRow, valueCol)).Value
Dim outputSize As Long
outputSize = ((UBound(inputArr, 1) - 1) * UBound(inputArr, 1)) / 2
Dim outputIndex As Long
Dim outputArr As Variant
ReDim outputArr(1 To outputSize, 1 To 1) As Variant
Dim i As Long
Dim n As Long
Dim currFirst As Long
Dim currLowest As Long
For i = 2 To UBound(inputArr, 1)
currFirst = inputArr(i, 1)
currLowest = currFirst - inputArr(i - 1, 1)
For n = i - 1 To 1 Step -1
Dim testLowest As Long
testLowest = currFirst - inputArr(n, 1)
If testLowest < currLowest Then currLowest = testLowest
outputIndex = outputIndex + 1
outputArr(outputIndex, 1) = currLowest
Next n
Next i
ws.Cells(startRow, outputCol).Resize(UBound(outputArr, 1)).Value = outputArr
End Sub
代码说明:(数据集仅用于视觉目的) 代码计算列(例如列 B)中的值并创建 array1 并将数组插入结果列。
我想要实现的是重复此代码/循环 n 次并创建动态数量的数组,然后将这些数组的结果放入 Result 列。我不知道如何在一个循环中创建一个 array1 然后 array2 等等。
一列可能有 60k+ 行,因此我需要非常轻量级的解决方案来实现最短运行时间。
感谢您的帮助。
编辑:
【问题讨论】:
-
在计算当前数组时,如果不依赖多个数组,为什么还需要多个数组?将整个过程主体包裹在
For n = 1 to n/Next中。 -
@GSerg 但是我会一直替换array1,不是吗?例如,我需要创建 10 个数组,然后比较其中的值。
-
列的长度是否不同?
-
@CDP1802 长度相同,数组大小相同
-
给定您的数据集,您可以使用公式获取结果列。并且有一些方法可以使其适应不同大小的数据集。