从方矩阵中选择列向量的函数

时间:2019-03-28 10:01:11

标签: excel vba

您好,我是VBA的新手,并创建了一些基本功能,但以下内容已被证明太高级了。

我想创建一个将方形矩阵转换为其列之一的函数。

      colA  colB   colC
[1,]   1      2      3
[2,]   4      5      6
[3,]   7      8      9

因此getcol(A1:C3,2)将输出:

2
5
8

我不确定是否可以从函数中输出范围。

将在数组Match函数中使用,因此:

{Index(G1:G3,Match(2&2,getcol(A1:C3)&getcol(D1:F3),0))}

我尝试过的代码肯定是没有道理的:

Function getcol(a As Range, b As Integer) As Range
getcol = Range(a).EntireColumn(b)
End Function

1 个答案:

答案 0 :(得分:0)

这是您要尝试的吗?我尚未使用索引/匹配进行测试。以下代码仅返回相关范围。如何使用它取决于您。

Option Explicit

Sub Sample()
    Dim rng As Range
    Dim truncRange As Range

    Set rng = Range("A1:C3")

    Set truncRange = getcol(rng, 2)

    If Not truncRange Is Nothing Then
        MsgBox truncRange.Address
    Else
        MsgBox "One of the parameters of getcol() is incorrect"
    End If
End Sub

Function getcol(a As Range, b As Integer) As Range
    Dim rowCount As Long

    '~~> Get the total rows in that range
    rowCount = a.Rows.Count

    '~~> Extract the range from relevant position
    Set getcol = Range(a.Cells(1, b), a.Cells(rowCount, b))
End Function