如何在 VBA 中有效地创建子数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10167495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 15:51:01  来源:igfitidea点击:

How to Create Subarray Efficiently in VBA?

excelexcel-vbavba

提问by Alpha

In my VBA program, I have a big array of data, where I need to constantly use its sub-arrays.

在我的 VBA 程序中,我有大量数据,我需要经常使用它的子数组。

My method is:

我的方法是:

Redim subArr(rowBegin to rowEnd)
For r = rowBegin to rowEnd
    subArr(r) = bigArr(r)
Next r

Is there any more efficient way to reference this kind of sub-arrays please? Thanks...

请问有没有更有效的方法来引用这种子数组?谢谢...

采纳答案by brettdj

Working with arrays is incredibly fast so this will probably give no discernable benefit - althouh I can understand how it may appeal from a coding sense than looping to fill a smaller array

使用数组的速度非常快,所以这可能不会带来明显的好处 - 虽然我可以理解它如何从编码意义上比循环填充更小的数组更有吸引力

Given you are working with a single element array you could:

鉴于您正在使用单个元素数组,您可以:

  1. Introduce a "marker" string inside the large array
  2. Jointhe large array with a delimiter into a single string
  3. Splitthe large array by the "marker" string, then separate the reduced string into a smaller array with the delimiter
  1. 在大数组中引入一个“标记”字符串
  2. Join带有分隔符的大数组变成单个字符串
  3. Split大数组由“标记”字符串组成,然后用分隔符将减少的字符串分成较小的数组

The code below dumps the numbers 1 to 100 into an array, and then splits it as above to pull out the first 10 records

下面的代码将数字 1 到 100 转储到一个数组中,然后像上面一样拆分它以取出前 10 条记录

Sub test()
Dim bigArr
Dim subArr
Dim strSep As String
Dim strDelim As String
Dim strNew As String
Dim rowBegin As Long
Dim rowEnd As Long

strDelim = ","
strSep = "||"
'fill array with 1 to 100
bigArr = Application.Transpose(Application.Evaluate("row(1:100)"))

rowBegin = 1
rowEnd = 10

bigArr(rowEnd + 1) = strSep
'make a single string
strNew = Join(bigArr, strDelim)
'split the string at the marker 
vArr = Split(strNew, strSep)
ReDim subArr(rowBegin To rowEnd)
'split the smaller string with the desired records
subArr = Split(Left$(vArr(0), Len(vArr(0)) - 1), strDelim)

End Sub

回答by chris neilsen

Short answer: probably not

简短回答:可能不是

Not quite so short answer: since you are creating a sub array with non 0/1 bounds, why not just pass a reference to the original array and the bounds?

不是那么简短的答案:既然您正在创建一个非 0/1 边界的子数组,为什么不只传递对原始数组和边界的引用?

BTW: a good resource for VBA array's is CPearson's site http://www.cpearson.com/excel/vbaarrays.htm

顺便说一句:VBA 阵列的一个很好的资源是 CPearson 的网站http://www.cpearson.com/excel/vbaarrays.htm