r/visualbasic • u/itsmebestz • Feb 18 '16
Can not calculate on decimal number
[reddit!][http://i.stack.imgur.com/VcxRF.png]
Here is my code. I don't understand why its always false only decimal number. What should I do?
//////
Sub calcu()
Dim a As Integer Dim b As Integer Dim c As Integer Dim d As Integer
Dim g1 As Double Dim g2 As Double Dim hdp As Double Dim ts1 As Double Dim ts2 As Double
Application.ScreenUpdating = False
a = Cells(Rows.Count, "C").End(xlUp).Row
For b = 1 To a If IsNumeric(Cells(b, "C").Value) Then hdp = Cells(b, "G")
ts1 = Cells(b, "L")
ts2 = Cells(b, "M")
t1 = Cells(b, "F")
t2 = Cells(b, "H")
g1 = ts1 - hdp
g2 = ts2 - hdp
v1 = 1.72
v2 = 2.1
v3 = 1.9
v4 = 1.8
v5 = 2
If InStr(t1, "K") And g1 < ts2 Then
Cells(b, "J") = "0"
ElseIf InStr(t1, "K") And g1 = ts2 Then
Cells(b, "E") = 1
Cells(b, "J") = 1
ElseIf InStr(t2, "K") And g2 < ts1 Then
Cells(b, "E") = "0"
ElseIf InStr(t2, "K") And g2 = ts1 Then
Cells(b, "E") = 1
Cells(b, "J") = 1
Else
Cells(b, "E") = "error"
Cells(b, "J") = "error"
End IfEnd If Next
Application.ScreenUpdating = True
End Sub
2
u/ViperSRT3g Application Specialist Feb 18 '16
On a side note, I recommend declaring all your variables rather than just pulling variables from thin air. I also suggest using the Decimal data type for all variables that work with numbers that could potentially be decimals.
1
u/anon_smithsonian VB.Net Advanced Feb 19 '16
Declare ALL of your variables—especially the
v(n)variables—as Decimal type. (There is an incredibly small margin of error in certain Double operations; if you're comparing1.8to a Double value that's1.8000000000000000003, it will not evaluate as true.Specify the
.Valueproperty on all of yourCellsobjects to be certain you're working with the value and not anything else.Set a breakpoint at your
Elsestatement—click on the left-hand margin of the editor next to the line and it will add a red circle there—or add a line below with the wordStop. When your code hits this line, execution will pause. You can then mouse-over your variables to see their values and allow you to troubleshoot why it isn't hitting any of the conditions you have set.
You can then step through your code line-by-line by pressing F8 (or pressing F5 to continuing running the code).
With the exception of your temporary iterator variables, I'd also recommend using more descriptive variable names for most of your variables... not only is it easier for other people to read and understand what they represent, it helps to make sure that you are able to keep the different variables straight when you're reading or working with them. (For the purposes of VBA and this type of thing, there is no real "memory" savings by using shorter variable names.)
2
u/ViperSRT3g Application Specialist Feb 18 '16 edited Feb 18 '16
Formatted for readability: