View Single Post
  #7   Report Post  
Posted to microsoft.public.excel.programming
Dave Peterson Dave Peterson is offline
external usenet poster
 
Posts: 35,218
Default limiting characters in a cell

First, please respond to your other thread in .misc that you have an active
thread in .programming. There is no reason to have other people work on a
solution if you find one here. And there is no reason for others to work on a
response here if you get a solution from that other post.

It's not fair to the responders to multipost like this.

But this seemed to work ok for me:

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)

Dim myRngToCheck As Range
Dim myCell As Range
Dim myLengths As Variant
Dim myCols As Variant
Dim iCol As Long

myCols = Array(1, 5, 12) 'A, E, L
myLengths = Array(10, 2, 5)

Set myRngToCheck = Me.Columns(myCols(LBound(myCols)))
For iCol = LBound(myCols) + 1 To UBound(myCols)
Set myRngToCheck = Union(myRngToCheck, Me.Columns(myCols(iCol)))
Next iCol

If Intersect(Target, myRngToCheck) Is Nothing Then
Exit Sub
End If

On Error Resume Next 'just keep going!
Application.EnableEvents = False
For Each myCell In Intersect(Target, myRngToCheck).Cells
'the arrays are 0 based, so we subtract 1 from the match
iCol = Application.Match(myCell.Column, myCols, 0) - 1
If Len(myCell.Value) myLengths(iCol) Then
myCell.Value = Left(myCell.Value, myLengths(iCol))
End If
Next myCell
Application.EnableEvents = True
On Error GoTo 0

End Sub




abouassi wrote:

thanks a lot for your help, you have solved half of my problem
the other part is because i don't know a lot in VBA(just how to write)
and it concerns how can i associate in the same code(or in different
codes)for every column different number of characters..anyways,i don't
have a lot of columns(about 10) so i can do it manually..the code you
gave me works perfectly well for only one column...
for example
i need column A to have 20 characters
column B to have 1 character
column C to have 19 character
......
......
and so on...
i appreciate your help, thank you

--
abouassi
------------------------------------------------------------------------
abouassi's Profile: http://www.excelforum.com/member.php...o&userid=37591
View this thread: http://www.excelforum.com/showthread...hreadid=572165


--

Dave Peterson