|
|
|
|
|
|
Excel
|
Cut and Paste into formatted cells
|
|
Ease of Use
|
Intermediate
|
Version tested with
|
2000, 2003
|
Submitted by:
|
mdmackillop
|
Description:
|
Copying/cutting and pasting in a formatted sheet results in the destination formatting being overwritten. The code below should preserve the formatting.
|
Discussion:
|
Wherever a sheet is pre-formatted, but the user needs to copy/paste or drag cell contents without "spoiling" the sheet setup.
|
Code:
|
instructions for use
|
Option Explicit
Private Sub Worksheet_Activate()
Application.EnableEvents = False
SaveFormat
Application.EnableEvents = True
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
GetFormat Target
Application.EnableEvents = True
End Sub
Option Explicit
Private Sub Workbook_Open()
Application.EnableEvents = True
FreezeChanges
End Sub
Private Sub Workbook_Beforeclose(Cancel As Boolean)
Dim sh As Worksheet
Application.DisplayAlerts = False
For Each sh In Sheets
If Right(sh.Name, 7) = "Formats" Then sh.Delete
Next
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Save
End Sub
Option Explicit
Sub FreezeChanges()
SaveFormat
[D3] = "Format frozen"
Application.EnableEvents = True
End Sub
Sub PermitChanges()
Application.EnableEvents = False
Application.DisplayAlerts = False
On Error Resume Next
Sheets(ActiveSheet.Name & "Formats").Delete
[D3] = "Changes permitted"
Application.DisplayAlerts = True
End Sub
Sub SaveFormat()
Dim MySht As String, MyAdd As String
Application.ScreenUpdating = False
MySht = ActiveSheet.Name
If ShExists(MySht & "Formats") = True Then GoTo DoSave
MyAdd = ActiveCell.Address
Sheets.Add
With ActiveSheet
.Name = MySht & "Formats"
.Visible = False
End With
DoSave:
Sheets(MySht).Cells.Copy
Sheets(MySht & "Formats").Range("A1").PasteSpecial Paste:=xlFormats
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
Sub GetFormat(Target As Range)
Dim MySht As String, MyCells As Range
Set MyCells = Selection
Application.ScreenUpdating = False
MySht = ActiveSheet.Name
Sheets(MySht & "Formats").Cells.Copy
Sheets(MySht).Range("A1").PasteSpecial Paste:=xlFormats
Application.CutCopyMode = False
Application.ScreenUpdating = True
MyCells.Select
End Sub
Function ShExists(ShName As String) As Boolean
Dim WS As Worksheet
On Error Resume Next
Set WS = Sheets(ShName)
If WS Is Nothing Then ShExists = False Else ShExists = True
End Function
|
How to use:
|
- Enter the code in relevant modules.
- Copy and paste cell contents into/out of formatted cells. The destination formatting should be preserved.
|
Test the code:
|
- Open the attachment
- Cut, Paste, drag fill etc data in the spreadsheet to differently formatted areas.
- Change formulae and check that correct values are being returned
- Test with absolute and relative values.
|
Sample File:
|
CutPasteFormat.zip 15.45KB
|
Approved by mdmackillop
|
This entry has been viewed 199 times.
|
|