I use this piece VBA code to truncate the input numbers in Excel but in some cases it still round the number rather than truncating them. When I try some specific numbers, it does NOT work. The examples I found are: 1.11116, 17.84116.
Please note that, the VBA is being applied to empty cells where an operator would enter data. That's why I can't simply use trunc(A1,4)
or similar commands.
These are the only numbers I came across that the code does not work on. Both end with a 6, but there is no pattern to the issue.
This is the code:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Const TARGET_RANGE As String = "A1:A10"
Const DECIMAL_PLACES As Long = 5
On Error GoTo ClearError
Dim irg As Range: Set irg = Interesect(Me.Range(TARGET_RANGE),Target)
If irg Is Nothing Then Exit Sub
Dim Num As Long: Num = 10^DECIMAL_PLACES
Application.EnableEvents = False
Dim iCell As Range, iValue, dValue As Double
For Each iCell In irg.Cells
iValue=iCell.Value
If VarType(iValue)=vbDouble Then
dValue=Int(iValue * Num)/Num
If dValue<iValue Then
iCell.Value=dValue
End If
End If
Next iCell
ProcExit:
On Error Resume Next
If Not Application.EnbaleEvents Then Application.EnableEvents = True
On Error GoTo O
Exit Sub
ClearError:
Resume ProcExit
End Sub
Does anyone have any ideas why this is happening and how to fix it? Thanks,
Please let me know if you have any ideas.