如何在VBA中使单元格“空白”而不是“空”

问题描述 投票:1回答:2

我使用Labview生成Excel报表,该报表基本上将数组粘贴到电子表格中。电子表格中存在空白,例如:

1
2
3

1
2
3

但是因为我在电子表格中插入一个数组,所以间隙是空的,但它们不是空白的。

当我使用“IsEmpty”运行vba代码检查每个单元格时,它返回true。但是,如果我使用“ISBLANK”运行excel公式,则返回false。我尝试过以下操作,但它不会使单元格空白。

If IsEmpty(Cells(r,c)) Then
    Cells(r,c).Value = ""
    Cells(r,c).ClearContents
    Cells(r,c) = ""

我想让细胞空白而不必删除它们。这是因为我试图在我的VBA代码中使用.End,但它并没有停留在差距上。

excel vba
2个回答
2
投票

你不需要检查IsEmpty(),而是:

If Cells(r, c).Value = "" Then Cells.ClearContents

这将删除Null。通过Nulls,我的意思是零长度字符串。


1
投票

这可能有点矫枉过正,但它对你有用:

Sub tgr()

    Dim ws As Worksheet
    Dim rClear As Range
    Dim aData As Variant
    Dim lRowStart As Long
    Dim lColStart As Long
    Dim i As Long, j As Long

    Set ws = ActiveWorkbook.ActiveSheet
    With ws.UsedRange
        If .Cells.Count = 1 Then
            ReDim aData(1 To 1, 1 To 1)
            aData = .Value
        Else
            aData = .Value
        End If
        lRowStart = .Row
        lColStart = .Column
    End With

    For i = LBound(aData, 1) To UBound(aData, 1)
        For j = LBound(aData, 2) To UBound(aData, 2)
            If Len(Trim(aData(i, j))) = 0 Then
                If rClear Is Nothing Then
                    Set rClear = ws.Cells(lRowStart + i - 1, lColStart + j - 1)
                Else
                    Set rClear = Union(rClear, ws.Cells(lRowStart + i - 1, lColStart + j - 1))
                End If
            End If
        Next j
    Next i

    If Not rClear Is Nothing Then rClear.ClearContents

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.