How to Solve runtime error 6 in vba?

2019-07-27 18:10发布

I have the following code

TextBox50.Value = Round((CDbl(TextBox3.Value) / (CDbl(Worksheets("calculation").Range("O4").Value)) - 1) * 100, 1) & "%"

The value of TextBox3 = Value present in Worksheets("calculation").Range("O4").

The issue is if the value of Range(O4) is zero, then it essentially means 0/0 which is why I am getting runtime 6, overflow error.

Is there anyway I can replace 0/0 with 0.

Any help is much appreciated. Thank you

2条回答
We Are One
2楼-- · 2019-07-27 18:31

Something like this should work for situation where you have a divide by zero issue:

If CDbl(Worksheets("calculation").Range("O4").Value) = 0 Then
   TextBox50.Value = (0 - 1) * 100, 1) & "%"
Else
    TextBox50.Value = Round((CDbl(TextBox3.Value) / (CDbl(Worksheets("calculation").Range("O4").Value)) - 1) * 100, 1) & "%"
End If
查看更多
劳资没心,怎么记你
3楼-- · 2019-07-27 18:35

You can use IIF():

TextBox50.Value = Round((CDbl(TextBox3.Value) / IIF(CDbl(Worksheets("calculation").Range("O4")=0,1,CDbl(Worksheets("calculation").Range("O4")))

Which will return the value in TextBox3 if the other is 0.

查看更多
登录 后发表回答