Consulting

Results 1 to 4 of 4

Thread: VBA: Copy Cell to another and remove last 2 characters

  1. #1

    VBA: Copy Cell to another and remove last 2 characters

    Hi,

    Could someone please tell me how to copy a text string from a cell in Excel and paste in to another minus the last two characters in VBA?

    For example if my original cell was 333.2cm, I would like the pasted cell to be 333.2

    Thanks

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Assuming your cell is formatted as text, otherwise fix the formatting.
    For Each cel In Selection
    cel.Offset(, 1) = Left(cel, Len(cel) - 2)
    Next
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  3. #3
    mdmackillop,

    That's great thanks. I have used:

    Sub Button1_Click()
    
    
    Range("D3,D10,D17,D24,D31,D38").Select
    For Each cel In Selection
    cel.Offset(, 8) = Left(cel, Len(cel) - 3)
    Next
    
    
    End Sub
    There will be up to 8 fields with the data in but not always. How do I stop it throwing up an error when if one of those cells are empty?

    Thanks
    Last edited by mdmackillop; 09-13-2017 at 03:59 AM. Reason: Code tags added

  4. #4
    Administrator
    VP-Knowledge Base VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Avoid selecting, refer to ranges directly
    Sub Button1_Click()
    For Each cel In Range("D3,D10,D17,D24,D31,D38")
    If Len(cel) > 3 Then cel.Offset(, 8) = Left(cel, Len(cel) - 3)
    Next
    End Sub
    Please use code tags when yoiu post code
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •