I need to repeatedly paste a specific line of text at the top of each cell in a column, while preserving existing text in those cells. This requires placing the cursor above the existing text.
I attempted to record a macro, but it only captures consecutive pastes, not the necessary cursor movement to the beginning of each cell in the column.
Can anyone suggest how to create a loop like:
' Text already copied
For each cell in ActiveTable.Column (3)
Paste
Next
To repeatedly paste a specific line of text at the top of each cell in a column while preserving existing text in those cells, you can use a loop in VBA. Here’s how you can accomplish this:
-
Setup:
- Open the Visual Basic Editor: Press Alt + F11 or navigate to the Developer tab and click Visual Basic in the Microsoft Office suite.
- Create a new module: In the Project Explorer (left pane), right-click on your workbook and select Insert > Module.
-
Code:
- Paste Special Values:
Sub PasteAtTopOfCells()
Dim targetRange As Range
Dim textToPaste As Variant
Dim cell As Range
' Text you want to paste
textToPaste = "Your line of text"
' Set target range (e.g., all cells in column 3)
Set targetRange = Range("C1", Range("C" & Rows.Count).End(xlUp))
' Loop through each cell in the target range
For Each cell In targetRange
' Store current value
Dim existingText As String
existingText = cell.Value
' Paste text at the top and combine with existing text
cell.Value = textToPaste & " " & existingText
Next cell
End Sub
-
Run:
- Run the macro: Click Run or press F5 in the Visual Basic Editor.
- Assign to a button (optional):
- Insert a button: Go back to your worksheet, click Insert, then Shapes, and choose any button.
- Right-click on the button, select Assign Macro, and choose your macro (
PasteAtTopOfCells
).
This macro will paste the specified text at the beginning of each cell in the specified range, keeping the existing text.