Search code examples
vbaexceltruncatedata-entry

Using Excel Macro to truncate in specified cells but still allow data entry in the same cell


I am completely new at working with Excel Macro but have encountered a spreadsheet issue at work that I believe may be solved by using a Macro formula. I need to truncate a value (cannot be rounded) to the second decimal place in specified cells. However, the values to be truncated must be entered by a third party using a template spreadsheet that the Macro formula will be attached to. Is there a way to lock a formula to certain cells while allowing data entry in those cells that would be updated by the formula? I have used the Macro below to successfully truncate cell values and now just need a way to force that Macro to run every time new data is input into the specified cells.

Sub TruncateSelection()
     ActiveSheet.Range("A1:A15").Select
Dim Cell As Range
     With Selection.Cells
        .Value = Evaluate("IF(ROW(1:" & Selection.Cells.Count & "),TRUNC(" & .Address & ",2))")
    End With
End Sub

Solution

  • You will need to bind your script to the Worksheet_Change event in VBA

    This MSDN article should shed some light on what you'll need to do.

    https://msdn.microsoft.com/en-us/library/office/ff839775.aspx