VBA 中的子数组 - 我想切掉一个维度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19897794/
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
Sub arrays in VBA - I want to slice a dimension off
提问by user2977592
Say I have a 2D array,
假设我有一个二维数组,
dim iArray(1 to 2, 1 to 2) as integer
iArray(1,1)=1: iArray(1,2)=2: iArray(2,1)=3: iArray(2,2)=4
'iArray = 1 2
' 3 4
and I want to cut one of the dimensions out.
In Matlab, you could:
我想剪掉其中一个维度。
在 Matlab 中,您可以:
%Matlab style:
cutArray = iArray(:,2)
%cutArray = 2
% 4
Is there an easy way to do this in VBA?
在 VBA 中是否有一种简单的方法可以做到这一点?
回答by chris neilsen
You can access a row or column from a 2D array using Application.Index(array, RowNum, ColNum)
您可以使用 2D 数组访问行或列 Application.Index(array, RowNum, ColNum)
to demonstrate
展示
Sub Demo()
Dim iArray(1 To 2, 1 To 2) As Integer
iArray(1, 1) = 1: iArray(1, 2) = 2: iArray(2, 1) = 3: iArray(2, 2) = 4
Dim aRow As Variant
Dim aCol As Variant
With Application
' Get Row 2
aRow = .Index(iArray, 2)
' Get Column 2
aCol = .Transpose(.Index(iArray, , 2))
End With
End Sub
回答by stobin
To my knowledge, you cannot do this without looping.
Below is an example of how you can do it by creating another array and filling it with a loop:
下面是一个示例,说明如何通过创建另一个数组并用循环填充它来完成此操作:
Sub arraySlice()
Dim i As Integer
Dim a1(1 To 2, 1 To 2) As Integer
a1(1, 1) = 1
a1(1, 2) = 2
a1(2, 1) = 3
a1(2, 2) = 4
Dim a2(1 To 2) As Integer
For i = 1 To UBound(a1)
a2(i) = a1(i, 2)
Next i
End Sub