Search code examples
excelvba

Excel Macro or VBA for Copy and pasting text


I need help writing a macro linked to a keyboard shortcut that says "copy the contents of the cell and add it to the contents of the cell above" e.g copy cell A2 (yacht) and add to contents in cell A1 (cool) so cell A1 will end with text "cool yacht"

Sadly, I don't have any meaningful code knowledge. But I can copy and paste any code to VBA and run it. This is the result I am getting from recording a macro: macro result In plain text:

Sub Macro5()
'
' Macro5 Macro
'
' Keyboard Shortcut: Ctrl+q
'
    ActiveCell.Select
    ActiveCell.FormulaR1C1 = ""
    ActiveCell.Offset(-1, 0).Range("A1").Select
    ActiveCell.FormulaR1C1 = "Sunday Ogundipe"
    ActiveCell.Offset(1, 0).Range("A1").Select
End Sub

The issue is that the macro recorded the whole sample result and will subsequently paste "cool yacht" whenever it is called instead of the variable content of the new cells.


Solution

  • Try this, it's not using copy/paste, but amends the cell values accordingly:

    With ActiveCell
        .Offset(-1, 0).Value = .Offset(-1, 0).Value & " " & .Value
    End With
    

    The above will error though, if you run this when active in row 1 as row 0 doesn't exist. So you can check this with:

    With ActiveCell
        If .Row > 1 Then .Offset(-1, 0).Value = .Offset(-1, 0).Value & " " & .Value
    End With