如何在VBA中检查第一个数组条目是否为空

时间:2019-05-30 09:01:08

标签: excel vba

下面的VBA代码将一系列单元格设置为commentArray,从数组中删除所有空白,并创建一个新的空白空闲数组,称为commentResults。然后,我想声明数组。

根据我的源数据,有可能该数组可能仍为空,因此下面的声明无效

thisws.Cells(i, 19).Resize(columnsize:=UBound(commentResults) - LBound(commentResults) + 1).Value = commentResults

所以我想我要添加一个检查(在debug.print之后的if语句),该检查仅在array(0)不为空的情况下才声明该数组,但我不断收到错误9,但我无法解决。

Dim commentArray(4) As Variant
    commentArray(0) = Cells(24, 4).Value
    commentArray(1) = Cells(25, 3).Value
    commentArray(2) = Cells(26, 3).Value
    commentArray(3) = Cells(27, 3).Value

'a and b as array loops
Dim a As Long, b As Long
Dim commentResults() As Variant

'loops through the array to remove blanks - rewrites array without blanks into commentArray
For a = LBound(commentArray) To UBound(commentArray)
    If commentArray(a) <> vbNullString Then
        ReDim Preserve commentResults(b)
        commentResults(b) = commentArray(a)
        b = b + 1
    End If
Next a

Debug.Print b

If IsError(Application.Match("*", (commentResults), 0)) Then
Else
    thisws.Cells(i, 19).Resize(columnsize:=UBound(commentResults) - LBound(commentResults) + 1).Value = commentResults
    b = 0
End If

对为什么这可能不起作用有任何想法吗?

我也尝试过:

If commentResults(0) <> vbNullString Then
    thisws.Cells(i, 27).Resize(columnsize:=UBound(commentResults) - LBound(commentResults) + 1).Value = commentResults
End If

1 个答案:

答案 0 :(得分:0)

Sub CommentArray()

Dim Comments As Range, c As Range
Set Comments = Union(Cells(24, 4), Range(Cells(25, 3), Cells(27, 3)))

Dim commentResults() As Variant
Dim i As Long

i = 0
For Each cell In Comments
    If cell.Value <> "" Then
        ReDim Preserve commentResults(i)
        commentResults(i) = cell.Value
        i = i + 1
    End If
Next cell

Dim debugStr As String

For i = LBound(commentResults) To UBound(commentResults)
    debugStr = debugStr & commentResults(i) & Chr(10)
Next i

MsgBox debugStr

End Sub

enter image description here