【发布时间】:2021-12-09 18:55:40
【问题描述】:
假设我有一个带有 X 值的 VBA 一维数组(或字典或集合)。我需要以 Y 为单位对这些值执行操作。
所以如果 X = 55 和 Y = 25,我需要循环 3 次:
- 选择值 1 到 25 并执行操作
- 选择 26 到 50 的值并执行操作
- 选择最后 5 个值并执行操作
任何具有良好性能的想法将不胜感激:)
编辑:
我想出了下面的代码。虽然看起来不是很简洁,但它可以工作
Sub test()
Dim arr As Variant
Dim temparr As Variant
Dim sippno As Integer
Dim loopend As Integer
Dim loopstart As Integer
Dim batchsize As Integer
Dim i As Integer
'Storing main array with all values
arr = Sheet1.Range("A1:A" & Sheet1.Range("A" & Rows.Count).End(xlUp).Row).Value
'Setting count of values, batch size and starting step for loop
sippno = WorksheetFunction.CountA(arr)
loopstart = 1
batchsize = 10
Do Until sippno = 0
If sippno < batchsize Then
loopend = loopstart + sippno - 1
Else
loopend = loopstart + batchsize - 1
End If
ReDim temparr(loopstart To loopend)
For i = loopstart To loopend
temparr(i) = WorksheetFunction.Index(arr, i, 0)
sippno = sippno - 1
Next
loopstart = loopend + 1
'Action to be performed with batch of values stored in second array
Debug.Print WorksheetFunction.TextJoin(", ", True, temparr)
Loop
End Sub
【问题讨论】:
-
你试过什么?请编辑您的问题并向我们展示您的代码尝试。