What function can I use in Excel VBA to slice an array?
相关问题
- How to get the maximum of more than 2 numbers in V
- Faster loop: foreach vs some (performance of jsper
- Convert Array to custom object list c#
- Excel sunburst chart: Some labels missing
- pick a random item from a javascript array
相关文章
- Numpy matrix of coordinates
- PHP: Can an array have an array as a key in a key-
- Get column data by Column name and sheet name
- Accessing an array element when returning from a f
- How can I convert a PHP function's parameter l
- How to make a custom list deserializer in Gson?
- programmatically excel cells to be auto fit width
- Recursively replace keys in an array
There is no direct
slice
function for arrays, different from many other recent languages.However, there is a short code snippet very handy for this. Below, a complete solution for 1D arrays:
For testing
The results
Here's a nifty function I wrote to subset a 2d array
You can use a combination of the Rows, Columns, Offset and Resize properties to get a subset of a range.
For example if you have a range that is 5 columns by 3 rows:
You can get any subset by appropriately combining the above properties. For example, if you want to get the rightmost 3 cells on the second row (i.e. "C2:E2" in the above example), you could do something like:
You could then wrap this up in a VBA function.
Two things, VBA doesn't support array slicing so whatever you use, you'll have to roll your own. But since this is just for Excel, you can use the build in worksheet function index for array slicing.
Below is a fast method to slice Excel variant arrays. Most of this was put together using the info from this excellent site http://bytecomb.com/vba-reference/
Essentially the destination array is pre-built as an empty 1d or 2d variant and passed to the sub with the source array and element index to be sliced. Due to the way arrays are stored in memory it's much faster to slice a column than a row as the memory layout allows a single block to be copied.
The good thing about this is it scales well beyond the Excel row limit.
Example usage:
Timings were on an old dual core CPU using the following test
Lance's solution has a bug in that it does not respect an offset start value with a sub-arry of unspecified length, I also found how it works quite confusing. I offer a (hopefully) more transparent solution below.