I have the following code, which I got from this community, which allows me to double click on a cell and insert a row below. It inserts the row then goes back to columns E through R, as well as column T, and clears contents.
All I want to do is take the same code and apply it to a button click instead of a double click (people here at work use double click to edit the cell).
Here's the double-click code:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True
Target.Offset(1).EntireRow.Insert
Target.EntireRow.Copy Target.Offset(1).EntireRow
Intersect(Target.Offset(1).EntireRow, Range("E:R,T:T")).ClearContents
End Sub
I tried several other codes (found on StackOverflow) that I was just going to modify to go back and ClearContents, but I keep getting errors.
Two other codes I've tried are:
Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub
and
Sub InsertRow()
r = Selection.Row
Cells(r + 1, 1).EntireRow.Insert
Cells(r, 1).Copy Destination:=Cells(r + 1, 1)
End Sub
On both, I get "Variable not defined" errors:
The end goal is for the user to click on a cell, click the button, it copies down the formulas from the line above, and then ClearContents in columns E through R, as well as column T (for only that newly inserted row, not ClearContents for the entire column!)
BONUS COOL POINTS: if you're able to make it so they can't add a row if they are above row 5, that'd be fantastic. Rows 1, 2, 3, and 4, are all header / information type rows, so if they click in any of those (or don't know the active cell is up there) and click this button, since you can't undo VBA, it could mess up the header section pretty good. So they would have to activate a cell in row 5 or below for this to work, that would be the icing on the cake.
Triple cool points if we can add a msg box that says "Please select a cell in row 5 or below" so they don't just think the button's broken... that would be the best of the best of the best.
Thanks for any help in advance!!


xlFormatFromLeftOrAboveorxlFormatFromRightOrBelow- documentation. And I'm assuming you haveOption Explicitat the top of your module (which is good), you must declare your variable before using it so insertingDim r As Longbeforer = Selection.Rowshould resolved it for your 2nd code.Ifstatement checking if the selected row is< 5, if true then[insert row code block...], else display aMsgBoxwith whatever you want to say.