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

时间:2017-08-27 17:31:17

标签: excel excel-vba vba

我有一系列我希望放入数组的数据。但是,此数据中有空白单元格,我不想将它们包含在我的数组中。

我已经创建了下面但是它没有用,我试图将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 

我在哪里错了?

2 个答案:

答案 0 :(得分:1)

所以这应该有效:

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

所以最新缺少的是一些定义,但最重要的是,数组只是通过输入一些值来定义它的大小。在VBA中,您必须使用ReDim来定义Array的大小,Preserve是为了保留Array中的值。如果你真的不需要它用于别的东西,我建议不要使用二维数组,因为你只能ReDim Array的最后一个维度。

答案 1 :(得分:1)

这里的要点是什么是&#34;空白&#34;?例如,Empty的单元格与包含vbNullString的单元格不同。

只有您确切知道 blank 对您的项目意味着什么,但一些常见的检查方法是:

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