-1

Here I have a difficult task for me. Any help will be appreciated. Thanks.

I have an excel sheet like this:

![enter image description here

I want to replace the ~ in column B and afterwords with the texts from column A. So that the result will be like this:

enter image description here

In the VBA code please ignore the color, I just use it for better representation.

I can understand the loop function is required. Please stop or jump out of the loop, when an empty cell is detected.

Thanks!

Community
  • 1
  • 1
Rita
  • 2,117
  • 3
  • 15
  • 15

2 Answers2

1

It's a bit quick and dirty, but it will get the job done

Sub ReplaceChar()

Dim toReplace As String
Dim ReplaceWith As String
Dim Col As Long
Dim lRow As Long


toReplace = "~"
ReplaceWith = "bbb"

' replacing all ~ from the first row
For lRow = 1 To Cells(Rows.Count, "B").End(xlUp).Row
    ' starting from Column B
    For Col = 2 To Cells(1, Columns.Count).End(xlToLeft).Column
        Cells(lRow, Col) = Replace(Cells(lRow, Col), toReplace, ReplaceWith)
    Next Col
Next lRow

End Sub
Shai Rado
  • 33,032
  • 6
  • 29
  • 51
1

Based on the layout from your images, you can try this code:

Sub ReplaceTextWithString()
Dim Text As String, Str As String, NewText As String
Dim LastRow As Long, iRow As Long, iCol As Long

LastRow = Cells(Rows.Count, 1).End(xlUp).Row    'Find the last row in column 1 (A)

For iRow = 2 To LastRow                         'Loop through column 1 from row 2 to LastRow
    Str = Cells(iRow, 1)                        'Set string value to replace "~"
    iCol = 2                                    'Initial value for a starting column
    Do                                          'Loop through columns in row iRow
        Text = Cells(iRow, iCol)
        NewText = Application.WorksheetFunction.Substitute(Text, "~", Str)
        Cells(iRow, iCol) = NewText
        iCol = iCol + 1
    Loop Until Cells(iRow, iCol) = vbNullString 'Loop until there's no cell to be replaced
Next
MsgBox "The task is 100% completed."            'Optional
End Sub

For future references, you might see: Excel VBA: How to remove substrings from a cell?

Community
  • 1
  • 1