Ok, that looks very helpful. I ran the sample program in a test file and it
worked great. Then I modified it for my purposes as below. I moved the
For-Next loop to after the offset but before the paste. I removed the Option
Explicit statement from my code because I don't know how to declare the i
variable correctly.
The trouble is, when I run the code, I still can't undo. Do you see any
errors below? How should I declare the i so I can still use Option Explicit?
'Custom data type for undoing
Type SaveRange
Val As Variant
Addr As String
End Type
' Stores info about current selection
Public OldWorkbook As Workbook
Public OldSheet As Worksheet
Public OldSelection() As SaveRange
Sub CopyFormula()
' Abort if a range isn't selected
If TypeName(Selection) <> "Range" Then Exit Sub
Dim myRng As Range
'single area at a time
Set myRng = Selection.Areas(1)
With Intersect(myRng.EntireRow, ActiveSheet.Range("r1").EntireColumn)
.Copy
With .Offset(0, -12)
' The next block of statements
' saves the current values for undoing
ReDim OldSelection(Selection.Count)
Set OldWorkbook = ActiveWorkbook
Set OldSheet = ActiveSheet
i = 0
For Each cell In Selection
i = i + 1
OldSelection(i).Addr = cell.Address
OldSelection(i).Val = cell.Formula
Next cell
.PasteSpecial Paste:=xlPasteValues
Selection.Style = "Calculation"
With .Resize(, 2) 'same number of rows, but two columns
.Replace What:="=", _
Replacement:="=", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
End With
End With
End With
Application.CutCopyMode = False
' Specify the Undo Sub
Application.OnUndo "Undo the CopyFormula macro", "UndoCopyFormula"
End Sub
Sub UndoCopyFormula()
' Undoes the effect of the CopyFormula sub
' Tell user if a problem occurs
On Error GoTo Problem
Application.ScreenUpdating = False
' Make sure the correct workbook and sheet are active
OldWorkbook.Activate
OldSheet.Activate
' Restore the saved information
For i = 1 To UBound(OldSelection)
Range(OldSelection(i).Addr).Formula = OldSelection(i).Val
Next i
Exit Sub
' Error handler
Problem:
MsgBox "Can't undo"
End Sub
"Dave Peterson" wrote:
> You can read some notes from John Walkenbach here:
> http://j-walk.com/ss/excel/tips/tip23.htm
>
> TKS_Mark wrote:
> >
> > After I run the command below, I can't undo. What change should I make to
> > make it undo-able.
> >
> > Thanks.
> >
> > Sub CopyFormula()
> >
> > Dim myRng As Range
> >
> > 'single area at a time
> > Set myRng = Selection.Areas(1)
> >
> > With Intersect(myRng.EntireRow, ActiveSheet.Range("r1").EntireColumn)
> > .Copy
> > With .Offset(0, -12)
> > .PasteSpecial Paste:=xlPasteValues
> > With .Resize(, 2) 'same number of rows, but two columns
> > .Replace What:="=", _
> > Replacement:="=", _
> > LookAt:=xlPart, _
> > SearchOrder:=xlByRows, _
> > MatchCase:=False, _
> > SearchFormat:=False, _
> > ReplaceFormat:=False
> > End With
> > End With
> > End With
> > Application.CutCopyMode = False
> > End Sub
>
> --
>
> Dave Peterson
>