用范围值填充数组,但如果单元格为空,则不填

我有一个充满数据的范围,我想把它放到一个数组中。 但是,这些数据中有空白单元格,我不想将它们包含在我的数组中。

我已经创build了下面,但它不工作,我试图把一个msgbox "if has been triggered"IF语句,并没有msgbox已经出现在运行这对我说'IF语句并没有实际触发。

 Dim rngAB As Range: Set rngAB = wsWeights.Range("AB4:AB" & wsWeights.Cells(Rows.count, "AB").End(xlUp).Row) Dim arr() As Variant k = 1 For Each cell In rngAB If cell.Value <> vbNullString Then arr(k, 1) = cell.Value k = k + 1 End If Next 

我在哪里错了?

这里的要点是“空白”是什么意思? 例如,一个Empty单元不同于包含vbNullString

只有你会知道你的项目到底是什么空白的手段,但一些常见的检查方法是:

 If IsEmpty() Then ... If Len(value) > 0 Then ... If Len(Trim(value)) > 0 Then ... If Trim(value & vbNullString) = vbNullString Then ... 

就你的代码而言,你需要在填充数组之前对数组进行维度定位。 一种方法,但绝不是唯一的方法,实现你的任务将如下(我已经承担了IsEmpty()情况):

 Dim r As Long Dim data As Variant, n As Variant Dim col As Collection Dim arr() As Variant 'Read sheet data into array. With Sheet1 data = .Range(.Range("AB4"), .Cells(.Rows.Count, "AB").End(xlUp)).Value2 End With 'Acquire the non-empty array indexes. Set col = New Collection For r = 1 To UBound(data, 1) 'We're using the IsEmpty() function. If Not IsEmpty(data(r, 1)) Then col.Add r 'Uncomment any of the below if you prefer to use them instead: 'If Len(data(r, 1)) > 0 Then col.Add r 'If Trim(data(r, 1) & vbNullString) = vbNullString Then col.Add r Next 'Dimension array to size of non-empty list. ReDim arr(1 To col.Count, 1 To 1) 'Populate the array r = 1 For Each n In col arr(r, 1) = data(CLng(n), 1) r = r + 1 Next 

所以这应该工作:

 Sub FillArrayNoBlanks() Dim ws As Worksheet, Cell As Range Dim rngAB As Range, k As Long: k = 0 Dim arr() As Variant Set ws = Worksheets(1) With ws Set rngAB = .Range("AB4:AB" & .Cells(.Rows.Count, "AB").End(xlUp).Row) End With For Each Cell In rngAB If Cell.Value <> vbNullString Then ReDim Preserve arr(k) arr(k) = Cell.Value k = k + 1 End If Next End Sub 

所以缺less的是一些定义,但最重要的是,数组并没有通过放入一些值来定义它的大小。 在VBA中,您必须使用ReDim来定义Array的大小, Preserve将保留Array的值。 如果你真的不需要它的东西,我wouldnt推荐使用2维数组,因为你只能ReDim数组的最后一个维度。