excel - 单列值最终出现在多维数组中

标签 excel vba

我正在使用来自列(范围)的一部分的值填充一个数组。结果数组是多维的 - 但它应该是一维的。我只想得到 Emp ID值到数组中:
enter image description here
我试过这个:

Sub Test()

Dim colPostionNumber As Integer
Dim lastRow As Integer
Dim ws As Worksheet
Dim positionNumberArray As Variant

Set ws = ActiveSheet

With ActiveWorkbook.Sheets("Sheet 1")
    colPositionNumber = Application.WorksheetFunction.Match("Emp ID", ws.Rows(5), 0)
    lastRow = ws.UsedRange.SpecialCells(xlCellTypeLastCell).row

positionNumberArray = .Range(Cells(5, colPositionNumber), Cells(lastRow, colPositionNumber)).Value

End With

End Sub 
但是结果数组是二维的
enter image description here
我尝试了 reDim,但没有奏效。如何使用一维数组执行此操作?

最佳答案

将一列二维数组写入一维数组
要获得从零开始的一维数组,您必须循环。

Sub Test()

    Dim colPositionNumber As Long
    Dim lastRow As Long
    Dim ws As Worksheet
    Dim Data As Variant
    Dim positionNumberArray As Variant
    
    Set ws = ActiveSheet
    
    With ActiveWorkbook.Sheets("Sheet 1")
        colPositionNumber = Application.Match("Emp ID", ws.Rows(5), 0)
        lastRow = ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row
        Data = .Range(.Cells(5, colPositionNumber), _
            .Cells(lastRow, colPositionNumber)).Value
        ReDim positionNumberArray(UBound(Data, 1) - 1)
        Dim n As Long
        For n = 1 To UBound(Data, 1)
            positionNumberArray(n - 1) = Data(n, 1)
        Next n
    End With

End Sub
使用 Application.Transpose
以下过程显示如何将一列或一行范围写入从一开始的一维数组:
Sub testATColumn()
    Dim rg As Range: Set rg = Range("A1:A5")
    Dim arr As Variant: arr = Application.Transpose(rg.Value)
    Debug.Print LBound(arr, 1), UBound(arr, 1)
    On Error Resume Next
    Debug.Print LBound(arr, 2), UBound(arr, 2)
    On Error GoTo 0
End Sub

Sub testATRow()
    Dim rg As Range: Set rg = Range("A1:E1")
    Dim arr As Variant
    arr = Application.Transpose(Application.Transpose(rg.Value))
    Debug.Print LBound(arr, 1), UBound(arr, 1)
    On Error Resume Next
    Debug.Print LBound(arr, 2), UBound(arr, 2)
    On Error GoTo 0
End Sub
请注意 Application.Transpose每个维度有 65535 个元素的限制。

关于excel - 单列值最终出现在多维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67083291/

相关文章:

javascript - 如何使用 table2excel 将带标题的表格导出到 Excel

VBA 工作表更改多个单元格

python - 如何使用python在excel中输入带有调​​度时间的日期?

excel - VBA 无法从 URL 打开 XML 文件,但可以处理下载的同一文件

excel - 如何修复计数 1 过多的 VBA 代码?

excel - 向 Excel 发送的大型 jasper 报告会导致文件损坏

vba - 内部 SAP 站点抓取出现自动化错误 : 800706B5, 80004005、80010108

VBA代码复制和粘贴事件列,其中合并单元格

SQL 比较 Access 中保存的日期与今天的日期不起作用

excel - 为什么选择范围变量时会发生变化?