如何將Excel中列的所有非空單元格作爲從偏移量開始的一維數組存儲在Excel中?如何通過偏移將列複製到數組?
例:
我希望將所有的細胞作爲單獨的項存儲在一個一維陣列 從Column B
偏離Row 3
開始。如果一個單元格是空的,我不想存儲它。
myArr = Range("B3:" & last_non_empty_cell_in_B).Value
如何將Excel中列的所有非空單元格作爲從偏移量開始的一維數組存儲在Excel中?如何通過偏移將列複製到數組?
例:
我希望將所有的細胞作爲單獨的項存儲在一個一維陣列 從Column B
偏離Row 3
開始。如果一個單元格是空的,我不想存儲它。
myArr = Range("B3:" & last_non_empty_cell_in_B).Value
使用一個Autofilter
在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
爲了使它返回一個字符串數組的函數:
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
不錯的20K :) –
@ShaiRado,我知道下一個是誰)。歡迎回來btw! –
@ A.S.H您的代碼可以創造奇蹟,謝謝!這不是問題的一部分,但爲什麼這不起作用? Dim arr()As String: arr = GetNonEmptyFromColumn(「B」,4)'這裏的函數是你的代碼返回myArr –
歡迎堆棧溢出,請[參觀](https://stackoverflow.com/tour),確保你閱讀[我如何提出一個好問題?](https://stackoverflow.com/help/how-to-ask)並用更多信息更新您的問題。 – lordrhodos
也請不要使用已過時的標籤。在使用標籤之前,瞭解標籤的全部內容:) –
謝謝!編輯 –