简体   繁体   中英

VBA: How to copy part of the string from one cell and replace part of another cell with it?

The text in excel I have looks like this:

[tab]SECTION 01.
*Name of section 1
TEXT
TEXT
TEXT
[tab]SECTION 2.
*Name of section 2
TEXT
...

I want to find next SECTION in column (1, 2, 3...), copy only string SECTION 01. (02., 03.,...,52.,...)and paste it in the cell below replacing only *.

The end result in excel should look like this:

SECTION 01. Name of section 1
TEXT
TEXT
TEXT
SECTION 02. Name of section 2
TEXT
...

I tried to record macro, but it only copies the same text to only one cell specified, so I will have to rearrange VB code. Can anyone help?

Thank you,

This code iterates column a ( col =1) and when it finds a '[tab]' it sets the sctn variable to the value of the cell (ignoring the '[tab]')

When it finds a '*', it replaces it with the content of the sctn variable

Dim row as Integer,col as Integer,sctn as String
col=1
row=1
While Cells(row,col)<>""
  If Instr(Cells(row,col),"[tab]")>0 Then
    sctn=Replace(Cells(row,col),"[tab]","")
    Cells(row,col)=sctn
  Else
    Cells(row,col)=Replace(Cells(row,col),"*",sctn)
  End If
  row=row+1
Wend

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