I've used this excellent code, which inserts rows into a table within a protected worksheet.
I want to make an amendment so instead of just inserting rows, it pastes the values of whatever is already on the clipboard. It still needs to insert these values (ie create the numbers of rows necessary to accommodate the data which is already in the selection)
End Sub
I want to make an amendment so instead of just inserting rows, it pastes the values of whatever is already on the clipboard. It still needs to insert these values (ie create the numbers of rows necessary to accommodate the data which is already in the selection)
VBA Code:
Sub AddTableRows()
'PURPOSE: Add table row based on user's selection
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
Dim rng As Range
Dim InsertRows As Long
Dim StartRow As Long
Dim InsideTable As Boolean
Dim RowToBottom As Boolean
Dim ReProtect As Boolean
Dim Password As String
Dim area As Range
'Optimize Code
Application.ScreenUpdating = False
'What is the worksheet password?
Password = ""
'Set Range Variable
On Error GoTo InvalidSelection
Set rng = Selection
On Error GoTo 0
'Unprotect Worksheet
With ActiveSheet
If .ProtectContents Or .ProtectDrawingObjects Or .ProtectScenarios Then
On Error GoTo InvalidPassword
.Unprotect Password
ReProtect = True
On Error GoTo 0
End If
End With
'Loop Through each Area in Selection
For Each area In rng.Areas
'Is selected Cell within a table?
InsideTable = IsCellInTable(area.Cells(1, 1))
'Is selected cell 1 row under a table?
RowToBottom = IsCellInTable(area.Cells(1, 1).Offset(-1))
'How Many Rows In Selection?
InsertRows = area.Rows.Count
'Selection Not Within Table?
If Not InsideTable And Not RowToBottom Then GoTo InvalidSelection
'Add Rows To Table
If InsideTable Then
'Which Row in Table is selected?
With area.Cells(1, 1)
x = .Row
y = .ListObject.DataBodyRange.Row
Z = .ListObject.DataBodyRange.Rows.Count
End With
StartRow = Z - ((y + Z - 1) - x)
'Insert rows based on how many rows are currently selected
For x = 1 To InsertRows
area.ListObject.ListRows.Add (StartRow)
Next x
ElseIf RowToBottom Then
For x = 1 To InsertRows
area.Cells(1, 1).Offset(-1).ListObject.ListRows.Add AlwaysInsert:=True
Next x
End If
Next area
'Protect Worksheet
If ReProtect = True Then ActiveSheet.Protect Password
Exit Sub
'ERROR HANDLERS
InvalidSelection:
MsgBox "You must select a cell within or directly below an Excel table"
If ReProtect = True Then ActiveSheet.Protect Password
Exit Sub
InvalidPassword:
MsgBox "Failed to unlock password with the following password: " & Password
Exit Sub
End Sub