How to get first two lines of text from a wraped cell?

15,576

Solution 1

I only need to get first two lines as 'wrapedtext1wrappedtext2' .Is it possible???

Yes it might be possible but there is NO SIMPLE way to achieve it. There are lot of factors that you will have to consider.

1) Row Height in Pixels

2) Font Type and Size

3) Line Spacing

4) Is the Cell Merged?

5) Is the cell in Autofit state

6) Is all the text in Normal mode or does it have any Bold/Italics/Underline character(s) etc etc

Consider this snapshot

enter image description here

For example, Row Height in Pixels can be derived from

Debug.Print Range("A1").Height * (24 / 18)

Font Size in the above case can be achieved from this

Debug.Print Range("A1").Font.Size

But the challenge is what would happen in the below scenario?

enter image description here

In my opinion, it would be too much of a pain to achieve what you want. The best part would be to use ALT + Enter to insert line breaks and then retrieve the text.

FOLLOWUP

The strings are entered into the wrapped cell through vba code. So How will insert data by pressing alt + enter? – 1355 4 hours ago

In such a scenario, you can take a similar approach as well.

Sub Sample()
    Dim strg As String

    strg = "This is a sample" & vbCrLf & _
           "sentence which is" & vbCrLf & _
           "in Cell A1 and the" & vbCrLf & _
           "text is separated" & vbCrLf & _
           "with line breaks"

    With Range("A1")
        .Columns(1).ColumnWidth = 16.86
        .Font.Name = "Calibri"
        .Font.Size = 11
        .Value = strg
    End With
End Sub

NOTE: For the above you will have to record a macro and see what is the font, font size and column width that can take a particular formatting. Again, you will have to consider the fact that the example that I have given above is for a non formatted cell in a new sheet. If you are writing to a merged cell or a per-formatted cell then you will have to change the above code accordingly which can be easily achieved by recording a macro. I am also assuming that the ZOOM level is set to 100%

SNAPSHOTS

enter image description here

HTH

Sid

Solution 2

Use the FIND function:

=LEFT(B2,(FIND(CHAR(10),B2)))

  • FIND searches for the line break character (CHAR(10)
  • LEFT gives you the first X characters in B2, up to the number where it finds the line break
Share:
15,576
divz
Author by

divz

Updated on June 14, 2022

Comments

  • divz
    divz almost 2 years

    I need to take the first two lines of text from a wrapped cell in Excel. For example, a wrapped Excel cell contains the text as follows:

    wrapedtext1
    
    wrappedtext2
    
    wrappedtext3
    
    wrappedtext4
    

    I need only the first two lines as 'wrapedtext1wrappedtext2'. Is it possible?