简体   繁体   中英

How to Solve runtime error 6 in vba?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM