What is the difference between .Value = “” and .ClearContents?

懵懂的女人 提交于 2020-01-03 07:40:33

问题


If I run the following code

Sub Test_1()
   Cells(1, 1).ClearContents
   Cells(2, 1).Value = ""
End Sub

When I check Cells(1, 1) and Cells(2, 1) using formula ISBLANK() both results return TRUE. So I'm wondering:

What is the difference between Cells( , ).Value = "" and Cells( , ).ClearContents?

Are they essentially the same?


If I then run the following code to test the time difference between the methods:

Sub Test_2()
Dim i As Long, j As Long
Application.ScreenUpdating = False

For j = 1 To 10
    T0 = Timer
    Call Number_Generator
    For i = 1 To 100000
        If Cells(i, 1).Value / 3 = 1 Then
            Cells(i, 2).ClearContents
           'Cells(i, 2).Value = ""
        End If
    Next i
    Cells(j, 5) = Round(Timer - T0, 2)
Next j

End Sub

Sub Number_Generator()
Dim k As Long
Application.ScreenUpdating = False

For k = 1 To 100000
    Cells(k, 2) = WorksheetFunction.RandBetween(10, 15)
Next k

End Sub

I get the following output for runtime on my machine

.ClearContents  .Value = ""
4.20            4.44
4.25            3.91
4.18            3.86
4.22            3.88
4.22            3.88
4.23            3.89
4.21            3.88
4.19            3.91
4.21            3.89
4.17            3.89

Based on these results, we see that the method .Value = "" is faster than .ClearContents on average. Is this true in general? Why so?


回答1:


From what I have found, if your goal is to simple have an empty cell and you do not want to change anything about the formatting, you should use Value = vbNullString as that is the most efficient.

The 'ClearContents' is checking and changing other properties in the cell such as formatting and the formula (which is technically a separate property than Value). When using Value = "" you are only changing one property and so it is faster. Using vbNullString prompts the compiler that you are using an empty string versus the other way with double quotes, it is expecting a general string. Because vbNullString prompts it to expect an empty string, it is able to skip some steps and you get a performance gain.




回答2:


You can notice a big difference in Excel spreadsheet.

Assume that B1 is filled by equation returns blank A1 = 5 B1 = "=if(A1=5,"","x")

In this case, you have to equations that you can write in C1 (1) C1 = <=isblank(B1)> (2) C1 =

Solution 1 will return false, as the cell is filled with equation Solution 2 will return True



来源:https://stackoverflow.com/questions/38455405/what-is-the-difference-between-value-and-clearcontents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!