Search This Blog

Sunday, August 28, 2011

Macro - ADD 3 rows & UNDO Macro to undo the addition of 3 rows

To do the following :

a) ADD 3 Rows
 (or even more rows) by prompting user to enter the number of rows they wish to insert.


b) UNDO MACRO:

1. Undo the addition/insertion of rows 


2. when click, it will also prompt: "Do you want to undo adding 3 rows ?" 

> Yes | Cancel
if Yes, macro proceed and if Cancel , macro will not run and remain.






Solution:

Option Explicit
Dim StartRow As Long
Dim RowCount

Sub InsertThreeRows()
Dim r As Long, n As Long
Dim c As Range
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
RowCount = InputBox("Enter number of row insertions", "Row Insertions", "10")
If RowCount = "" Then Exit Sub
  If Selection.Rows.Count > 1 Then
    MsgBox "Select only one Row!", vbExclamation
    Exit Sub
  End If
  r = Selection.Row
  StartRow = r
  For n = 1 To RowCount
    Range(Cells(r + 1, 1), Cells(r + 3, 1)).EntireRow.Insert
    For Each c In Intersect(ActiveSheet.UsedRange, Rows(r)).Cells
      If c.HasFormula Then c.AutoFill Range(c, c.Offset(3, 0))
    Next
    r = r + 4
  Next
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

Sub UndoThreeRows()
If RowCount = 0 Then Exit Sub
Dim r As Long, rus As String
rus = MsgBox("Do you want to undo adding 3 rows ?", vbYesNo)
If rus = vbNo Then Exit Sub
For r = StartRow To (StartRow + RowCount)
Range(Rows(r).Offset(1, 0), Rows(r).Offset(3, 0)).Delete
Next
End Sub

No comments:

Post a Comment