VBA 多维数组 [英] VBA Multidimensional Arrays

查看:158
本文介绍了VBA 多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 VBA 中执行以下操作?

Is there a way to do the following in VBA?

初始化一个多维数组并用一系列数字填充它,

Initialize a multidimensional array and fill it with a series of numbers,

 1  2  3  4  5 
 6  7  8  9 10
11 12 13 14 15
16 17 18 19 20

然后删除一些特定的列,例如.第 1、2、4 列.因此最终结果只是第 3 和第 5 列.

Then remove some specific columns, for eg. columns 1, 2, 4. So that the end result is just the 3rd and 5th column.

最后如何将最终输出转换为普通的一维数组.

Lastly how does one convert the final output to a normal one dimensional array.

推荐答案

假设您在 Excel 工作表中有这些列.如果您在这些列中只有这些数据,您可以简单地删除您需要的列 :D 然后您将得到 2 个您想要的列.不知道你最后真正需要什么,这是最好的盲目猜测..

Assume that you have these columns in an Excel sheeet. If you only have these data in these columns you may simple delete the columns you need :D Then you will end up with 2 columsn you desire. Without knowing what you really need at the end this is the best blind guess..

例如您的列从 B 到 F:

e.g. your columns starts at B to F:

Columns("B:B").Delete Shift:=xlToLeft
Columns("C:C").Delete Shift:=xlToLeft
Columns("D:D").Delete Shift:=xlToLeft

您可以使用相同的逻辑来处理数组.

You can use the same logic to process the array.

  • 将数组转置到工作表中.
  • 删除列.
  • 然后将左边的两列转置为数组.

但是如果不将最后两列放入工作表,您将如何处理它?非常好奇.所以请确认您需要什么,以便这里的任何人都可以帮助您.

But what will you do with the last two columns without putting it into the sheet? Very curious. So please confirm what you need, so anyone here can help you.

根据 OP 的评论进行

EDIT as per OP's comment:

你可以看看这篇文章和文章,它们以不同的方式操作数组:

You may take a look at this posts and articles which has manupulation of arrays in different ways:

然后为了在 VBA 中为示例填充二维数组,请查看:

Then in order to populate a 2D array for an example in VBA, check this out:

Dim i As Integer, j As Integer
Dim array2D As Variant, newArray2D as Variant
'-- 0 indexed based array with 2 rows 3 columns
ReDim array2D(0 To 1, 0 To 2)

For i = LBound(array2D, 1) To UBound(array2D, 1)
    For j = LBound(array2D, 1) To UBound(array2D, 1)
        array2D(i, j) = i + j
    Next j
Next i

'--to delete the fastest is to use the above logic (worksheet)
'-- here you don't need to declare/redimentioned the array
'-- as transpose will do it with a 1 indexed based array

newArray2D = WorksheetFunction.Transpose(Sheets(2).Range("B2:D").Value)

这篇关于VBA 多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆