'VBA: Sheet formatting and formulas disrupted upon insertion of many rows
I am trying to create a VBA code in which user can insert multiple rows at the click of a button in a protected sheet. The number of rows to be inserted depends on user input. The code below works fine for 1-4 rows.
For insertion of 5 rows and above, the code will still run and correct number of rows will be inserted, but the formatting of the table and subtotal formulas at the bottom of the table will will be disrupted.
Some examples of the disruptions include, the borders disappearing for some cells and color fills overrunning into other cells that are not meant to be colored. The subtotal cells will also show "#VALUE!". I'm using INDIRECT function in the subtotal cells to take into account addition of new rows.
Would appreciate any help on this!
Code used:
Sub InsertRows()
Application.ScreenUpdating = False
' Unprotect the sheet
ActiveSheet.Unprotect "abc123"
Dim numRows As Integer
Dim counter As Integer
'Select the current row
ActiveCell.EntireRow.Select
On Error GoTo Last
numRows = InputBox("Enter number of rows to insert", "Insert Rows")
'Keep on inserting rows until we reach the desired number
For counter = 1 To numRows
Selection.Insert Shift:=xlToDown, CopyOrigin:=xlFormatFromRightorAbove
' Fill down the formula from above the inserted row to below it
Range("F" & (ActiveCell.Row - 1) & ":F" & (ActiveCell.Row + numRows)).FillDown 'Total SP
Range("J" & (ActiveCell.Row - 1) & ":J" & (ActiveCell.Row + numRows)).FillDown 'Unit Cost
Range("K" & (ActiveCell.Row - 1) & ":K" & (ActiveCell.Row + numRows)).FillDown 'Total Cost
Next counter
'ExitHandler:
' Protect the sheet again
ActiveSheet.Protect _
Password:=("abc123"), _
AllowFormattingColumns:=True, _
AllowFormattingRows:=True
Last: Exit Sub
Application.ScreenUpdating = True
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
