简体   繁体   中英

Insert line break before a specific word vba

Is it possible, through vba, to identify a specific word in the wrapped text cell; and insert a line break just before that specific work so it will end up on the next line? Assume the word I am trying to push to the next line is "block"

I don't even know where to start with code on this. If I had to guess I would think....

If instr(range a1:a,"block",1) then
   Chr(10)

Or something of that sort. Not sure what my declarations would look like either.

There may be a better way to do this but my first thought would be to split the string into an array, then re-build the string by looping through the array elements to find the word you're looking for and add the line break before it.

You may have to change the cell references but this should get you started:

Sub addLineBreak()

    Dim oldString As String
    Dim newString As String
    Dim brkString As String
    
    Dim strArray As Variant
    
    Dim i As Long
    
    ' Location of string to split
    oldString = Range("A1").Value
    
    ' Word to add line break before (lowercase)
    brkString = "block"
    
    strArray = Split(oldString, " ")
    
    For i = 0 To UBound(strArray)
        If LCase(strArray(i)) = brkString Then
            newString = newString & Chr(10) & strArray(i)
        Else
            newString = newString & " " & strArray(i)
        End If
                
    Next
    
    newString = Right(newString, Len(newString) - 1)
    
    ' Location to dump new string
    Range("A1").Value = newString
    
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM