PDA

View Full Version : auto run a macro upon text entry into cell



rackle
09-16-2011, 08:11 AM
How do I make this code automatically run after a user enters data into a cell? I have zero experience with this so I need simple instructions.

''Simulates row height autofit for a merged cell if the active cell..
'' is merged.
'' has Wrap Text set.
'' includes only 1 row.
''Unlike real autosizing the macro only increases row height
'' (if needed). It does not reduce row height because another
'' merged cell on the same row may needed a greater height
'' than the active cell.
Sub AutoFitMergedCellRowHeight()
Dim CurrentRowHeight As Single, MergedCellRgWidth As Single
Dim CurrCell As Range
Dim ActiveCellWidth As Single, PossNewRowHeight As Single
If ActiveCell.MergeCells Then
With ActiveCell.MergeArea
If .Rows.Count = 1 And .WrapText = True Then
Application.ScreenUpdating = False
CurrentRowHeight = .RowHeight
ActiveCellWidth = ActiveCell.ColumnWidth
For Each CurrCell In Selection
MergedCellRgWidth = CurrCell.ColumnWidth +
MergedCellRgWidth
Next
.MergeCells = False
.Cells(1).ColumnWidth = MergedCellRgWidth
.EntireRow.AutoFit
PossNewRowHeight = .RowHeight
.Cells(1).ColumnWidth = ActiveCellWidth
.MergeCells = True
.RowHeight = IIf(CurrentRowHeight > PossNewRowHeight, _
CurrentRowHeight, PossNewRowHeight)
End If
End With
End If
End Sub

Rob342
09-18-2011, 10:32 AM
Rackle

Use Worksheet selection change event and insert your sub ie


Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Call AutoFitMergedCellRowHeight
End Sub

rackle
09-19-2011, 08:04 AM
what if I want to apply this to the whole sheet so all cells auto-expand when text is entered?

Rob342
09-19-2011, 01:30 PM
Rackle

The question was to auto activate the sub routine
Merged cells always create problems and diff to code, best to steer clear if you can do without them.

Why would you want this to apply to all the sheet?

rackle
09-20-2011, 04:36 AM
I actually want the target cell to expand not the active cell so if I understand correctly I need to change all parts of the code that say 'active cell' to 'target'