如何通过偏移将列复制到数组?

如何将一列中的所有非空单元格作为从偏移量开始的一维数组存储在Excel中?

例如

我想将所有的单元格作为单独的项目存储在从Column B Row 3开始的Column B中的一维数组中。 如果一个单元格是空的,我不想存储它。

 myArr = Range("B3:" & last_non_empty_cell_in_B).Value 

在列B上使用自动Autofilter ,然后将可见单元格复制到数组中

 Sub columnB() Dim B As Range, cel As Range, i As Long, myArr With Sheet1 Set B = .Range("B3", .Cells(.Rows.Count, "B").End(xlUp)) B.AutoFilter 1, "<>" ' <-- autofilter out blank cells ReDim myArr(B.SpecialCells(xlCellTypeVisible).Count - 1) ' <-- size the array accordingly For Each cel In B.SpecialCells(xlCellTypeVisible) ' <-- copy cells individually to array myArr(i) = cel.Value2 i = i + 1 Next .Cells.AutoFilter ' now remove the autofilter End With ' now you have you array myArr End Sub 

使其成为返回string数组的函数:

 Function GetNonEmptyFromColumn(col As String, headerRow As String) As String() Dim B As Range, cel As Range, i As Long, myArr() As String With Sheet1 Set B = .Range(col & headerRow, .Cells(.Rows.Count, col).End(xlUp)) B.AutoFilter 1, "<>" ' <-- autofilter out blank cells ReDim myArr(B.SpecialCells(xlCellTypeVisible).Count - 1) As String ' <-- size the array accordingly For Each cel In B.SpecialCells(xlCellTypeVisible) ' <-- copy cells individually to array myArr(i) = cel.Value2 i = i + 1 Next .Cells.AutoFilter ' now remove the autofilter End With GetNonEmptyFromColumn = myArr ' now you have you array myArr End Function Sub Test() Dim s() As String s = GetNonEmptyFromColumn("B", 4) End Sub