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

时间:2017-06-15 07:34:32

标签: arrays excel excel-vba vba

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

示例

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

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

1 个答案:

答案 0 :(得分:1)

在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

使它成为一个返回字符串数组的函数:

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
相关问题