vba 如果公式返回空白值,如何清除单元格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24748762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:51:17  来源:igfitidea点击:

How to clear cell if formula returns blank value?

excelvba

提问by Neo Yi Peng

I have a formula like this:

我有一个这样的公式:

 if(A1="","",1)

How do I do a quick search to remove the formula if it is ""? I tried searching for blanks, but because there is a formula, it does not return a blank.

如果是公式,我该如何快速搜索以删除公式""?我尝试搜索空格,但因为有一个公式,它不会返回一个空格。

回答by hnk

You need to use the following code

您需要使用以下代码

Sub ClearCell()
    Dim Rng As Range
    Set Rng = ActiveSheet.Range("A1")

    Dim i As Long
    For i = 1 To 10
        If Rng.Cells(i,1) = "" Then
           Rng.Cells(i,1).ClearContents
        End If
    Next i
End Sub

That will leave the cell truly EMPTYand not with a zero-character ""string.

这将真正留下单元格,EMPTY而不是零字符的""字符串。

If you are looking to clear arbitrary length whitespace in cells, use

如果您想清除单元格中任意长度的空白,请使用

If Len(Trim(Rng.Cells(i,1))) = 0 Then
' .....

This condition will be true for any number of spaces or no spaces (empty string). That way (almost) anything which looks blank will get cleared.

对于任意数量的空格或没有空格(空字符串),此条件都为真。这样(几乎)任何看起来空白的东西都会被清除。