Home > OS >  Add a text to an existing cell
Add a text to an existing cell

Time:01-18

I'm trying to create a function in VBA to add a text to an existing cell.

For Example

I want to add "Brand" to cells in the first column. I want to use this function in any cell where I enter the formula.

I'm very new to VBA. I tried searching the internet but couldn't find a simple solution for my level. Could anyone please help me with this?  Thank you

CodePudding user response:

Select the first cell you want to change before running the code.

Sub insertBrand()

Do While ActiveCell.Value <> ""
    ActiveCell.Value = "Brand " & ActiveCell.Value
    Cells(ActiveCell.Row   1, ActiveCell.Column).Activate
Loop

End Sub

CodePudding user response:

Add a new module in the Visual Basic Editor (VBE).

Add this code to the module:

Option Explicit

Public Sub Add_Brand()

    Dim Cell As Range
    For Each Cell In Selection
        Cell = "Brand " & Cell
    Next Cell

End Sub

Select a range of cells, go to View > Macros on the toolbar and run the Add_Brand macro.

Edit: I should add that if the selected range of cells contain a formula then this will overwrite the formula with the new value.

Edit 2: If you did have formula (not an array formula) I guess you could use this code....

Public Sub Add_Brand()

    Dim Cell As Range
    For Each Cell In Selection
        If Cell.HasFormula Then
            Cell.Formula2 = "=""Brand "" & " & Mid(Cell.Formula2, 2, Len(Cell.Formula2))
        Else
            Cell = "Brand " & Cell
        End If
    Next Cell

End Sub
  • Related