如何將一個列復制到一個數組中?

[英]How to copy a column to an array by offset?


How to store all non empty cells from a column in Excel as a one-dimensional array starting from an offset?

如何將Excel中的列中的所有非空單元格存儲為從偏移量開始的一維數組?

Example:

例子:

I want to store all cells as individual items in a one-dimensional array from Column B starting from offset Row 3. If a cell is empty I do not want to store it.

我想將所有單元格作為單個項目存儲在從第3行開始的B列的一維數組中。如果一個單元格是空的,我不想存儲它。

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

1 个解决方案

#1


1  

Use an Autofilter on column B then copy the visible cells to the array

在B列上使用自動過濾器,然后將可見單元格復制到數組中

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

To make it a function that returns an array of strings:

使其成為返回字符串數組的函數:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/06/15/720b086483b2ea7ca11a32ccf9ba6bca.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com