Vba copy formatting excel

Remember that when you write:

MyArray = Range("A1:A5000")

you are really writing

MyArray = Range("A1:A5000").Value

You can also use names:

MyArray = Names("MyWSTable").RefersToRange.Value

But Value is not the only property of Range. I have used:

MyArray = Range("A1:A5000").NumberFormat

I doubt

MyArray = Range("A1:A5000").Font

would work but I would expect

MyArray = Range("A1:A5000").Font.Bold

to work.

I do not know what formats you want to copy so you will have to try.

However, I must add that when you copy and paste a large range, it is not as much slower than doing it via an array as we all thought.

Post Edit information

Having posted the above I tried by own advice. My experiments with copying Font.Color and Font.Bold to an array have failed.

Of the following statements, the second would fail with a type mismatch:

  ValueArray = .Range("A1:T5000").Value
  ColourArray = .Range("A1:T5000").Font.Color

ValueArray must be of type variant. I tried both variant and long for ColourArray without success.

I filled ColourArray with values and tried the following statement:

  .Range("A1:T5000").Font.Color = ColourArray

The entire range would be coloured according to the first element of ColourArray and then Excel looped consuming about 45% of the processor time until I terminated it with the Task Manager.

There is a time penalty associated with switching between worksheets but recent questions about macro duration have caused everyone to review our belief that working via arrays was substantially quicker.

I constructed an experiment that broadly reflects your requirement. I filled worksheet Time1 with 5000 rows of 20 cells which were selectively formatted as: bold, italic, underline, subscript, bordered, red, green, blue, brown, yellow and gray-80%.

With version 1, I copied every 7th cells from worksheet «Time1» to worksheet «Time2» using copy.

With version 2, I copied every 7th cells from worksheet «Time1» to worksheet «Time2» by copying the value and the colour via an array.

With version 3, I copied every 7th cells from worksheet «Time1» to worksheet «Time2» by copying the formula and the colour via an array.

Version 1 took an average of 12.43 seconds, version 2 took an average of 1.47 seconds while version 3 took an average of 1.83 seconds. Version 1 copied formulae and all formatting, version 2 copied values and colour while version 3 copied formulae and colour. With versions 1 and 2 you could add bold and italic, say, and still have some time in hand. However, I am not sure it would be worth the bother given that copying 21,300 values only takes 12 seconds.

** Code for Version 1**

I do not think this code includes anything that needs an explanation. Respond with a comment if I am wrong and I will fix.

Sub SelectionCopyAndPaste()

  Dim ColDestCrnt As Integer
  Dim ColSrcCrnt As Integer
  Dim NumSelect As Long
  Dim RowDestCrnt As Integer
  Dim RowSrcCrnt As Integer
  Dim StartTime As Single

  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual
  NumSelect = 1
  ColDestCrnt = 1
  RowDestCrnt = 1
  With Sheets("Time2")
    .Range("A1:T715").EntireRow.Delete
  End With
  StartTime = Timer
  Do While True
    ColSrcCrnt = (NumSelect Mod 20) + 1
    RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
    If RowSrcCrnt > 5000 Then
      Exit Do
    End If
    Sheets("Time1").Cells(RowSrcCrnt, ColSrcCrnt).Copy _
                 Destination:=Sheets("Time2").Cells(RowDestCrnt, ColDestCrnt)
    If ColDestCrnt = 20 Then
      ColDestCrnt = 1
      RowDestCrnt = RowDestCrnt + 1
    Else
     ColDestCrnt = ColDestCrnt + 1
    End If
    NumSelect = NumSelect + 7
  Loop
  Debug.Print Timer - StartTime
  ' Average 12.43 secs
  Application.Calculation = xlCalculationAutomatic

End Sub

** Code for Versions 2 and 3**

The User type definition must be placed before any subroutine in the module. The code works through the source worksheet copying values or formulae and colours to the next element of the array. Once selection has been completed, it copies the collected information to the destination worksheet. This avoids switching between worksheets more than is essential.

Type ValueDtl
  Value As String
  Colour As Long
End Type

Sub SelectionViaArray()

  Dim ColDestCrnt As Integer
  Dim ColSrcCrnt As Integer
  Dim InxVLCrnt As Integer
  Dim InxVLCrntMax As Integer
  Dim NumSelect As Long
  Dim RowDestCrnt As Integer
  Dim RowSrcCrnt As Integer
  Dim StartTime As Single
  Dim ValueList() As ValueDtl

  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual

  ' I have sized the array to more than I expect to require because ReDim
  ' Preserve is expensive.  However, I will resize if I fill the array.
  ' For my experiment I know exactly how many elements I need but that
  ' might not be true for you.
  ReDim ValueList(1 To 25000)

  NumSelect = 1
  ColDestCrnt = 1
  RowDestCrnt = 1
  InxVLCrntMax = 0      ' Last used element in ValueList.
  With Sheets("Time2")
    .Range("A1:T715").EntireRow.Delete
  End With
  StartTime = Timer
  With Sheets("Time1")
    Do While True
      ColSrcCrnt = (NumSelect Mod 20) + 1
      RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
      If RowSrcCrnt > 5000 Then
        Exit Do
      End If
      InxVLCrntMax = InxVLCrntMax + 1
      If InxVLCrntMax > UBound(ValueList) Then
        ' Resize array if it has been filled 
        ReDim Preserve ValueList(1 To UBound(ValueList) + 1000)
      End If
      With .Cells(RowSrcCrnt, ColSrcCrnt)
        ValueList(InxVLCrntMax).Value = .Value              ' Version 2
        ValueList(InxVLCrntMax).Value = .Formula            ' Version 3
        ValueList(InxVLCrntMax).Colour = .Font.Color
      End With
      NumSelect = NumSelect + 7
    Loop
  End With
  With Sheets("Time2")
    For InxVLCrnt = 1 To InxVLCrntMax
      With .Cells(RowDestCrnt, ColDestCrnt)
        .Value = ValueList(InxVLCrnt).Value                 ' Version 2
        .Formula = ValueList(InxVLCrnt).Value               ' Version 3
        .Font.Color = ValueList(InxVLCrnt).Colour
      End With
      If ColDestCrnt = 20 Then
        ColDestCrnt = 1
        RowDestCrnt = RowDestCrnt + 1
      Else
       ColDestCrnt = ColDestCrnt + 1
      End If
    Next
  End With
  Debug.Print Timer - StartTime
  ' Version 2 average 1.47 secs
  ' Version 3 average 1.83 secs
  Application.Calculation = xlCalculationAutomatic

End Sub

Skip to content

Excel VBA Copy Range to Another Sheet with Formatting

Home » Excel VBA » Excel VBA Copy Range to Another Sheet with Formatting

  • VBA Copy Range to Another Sheet

Very often we need to copy the Excel Range to another sheet with formatting. We can use VBA to automate this task.  Excel VBA Copy Range to Another Sheet with Formatting macro is explained to know how to copy a range to another worksheet using VBA.

How to Copy Range to Another Sheet with Formatting in Excel VBA

Here is the ‘Excel VBA Copy Range to Another Sheet with Formatting‘ macro to copy a range to another sheet with formatting. You can clearly observe that the Excel VBA is copying the given range to another sheet.

Sub Excel_VBA_Copy_Range_to_Another_Sheet_with_Formatting()
Range("A1:E21").Copy Destination:=Sheets("AnotherSheet").Range("A1")
End Sub

Excel VBA Copy Range to Another Sheet with Formatting

The above example macro will copy the given range to another sheet. Macro will copy the Range A1:A21 and paste at Range A1 of Another Sheet. You can edit the sheet name and range to suit your requirement. You can clearly see form the two sheets and notice these points:

  • The macro is perfectly copying the range of data to another sheet
  • It is also copying the Format of the given range to destination sheet.
  • But not the column width.

How to copy the Excel Range including Column widths

It is easy to copy Excel Range to another sheet with formatting and column widths. We have theree solutions, you can implement one of this to suite your process automation.

Method 1: Using PasteSpecial Method to Copy Range and Paste in Another Sheet with Formatting and Column Widths.

Sub Excel_VBA_Copy_Range_to_Another_Sheet_with_Formatfting_ColumnWidth()

Range("A1:E21").Copy Destination:=Sheets("AnotherSheet").Range("A1")
Range("A1:E21").Copy
Sheets("AnotherSheet").Range("A1").PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False

End Sub

Excel VBA Copy Range to Another Sheet with Formatting Column Width

Method 3: Copying Entire Range of Columns and Paste in Another Sheet.

We copy entire columns of the required range and paste in another sheet. This approach is useful when there is no other data in both the sheets. This will copy range of data including Formatting and Column Widths. Please check the following macro to copy both formatting and column widths.

Sub Excel_VBA_Copy_Range_to_Another_Sheet_with_FormattingAndColumnWidths()

Range("A:E").Copy Destination:=Sheets("AnotherSheet2").Range("a1")
End Sub

The only change in this method is, removing the row numbers from the ranges (A1:E21) and just using the columns A:E.

Method 3: Explicitly specifying the Column Widths

The following macro will copy the range and paste into another sheet. This will also make copy the Formatting and Column widths of the given Range.

Sub Excel_VBA_Copy_Range_to_Another_Sheet_with_FormattingForEachColumn()
Range("A1:E21").Copy Destination:=Sheets("AnotherSheet").Range("a1")
colCntr = 0
For Each col In Range("A1:E21").Columns
Sheets("AnotherSheet").Range("A1").Offset(1, colCntr).ColumnWidth = col.ColumnWidth
colCntr = colCntr + 1
Next
End Sub

Copy Range Values to Another Sheet with out Formatting in Excel VBA

We may need to copy only the values of the given range to another sheet with no formatting. You can copy and paste only values into the another sheet using Excel VBA.

The following macro will copy a range and paste only values in another sheet.

Range("A1:E21").Copy

Sheets("AnotherSheet").Range("A1").PasteSpecial _
Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

Copy Formats of a Range to Another Sheet using Excel VBA

Alternatively, we can also paste only the formats of the given range into another sheet. We can copy the range use pastespecial method to paste only formats of the source range using Excel VBA.

Here is the macro will copy a range and paste only the formats in another sheet.

Sheets("AnotherSheet").Range("A1").PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False

Copy Formulas of a Range to Another Sheet using Excel VBA

Sometimes, we may need copy the formulas of the given range and paste in to another range. PasteSpecial method allows us to paste only Formulas to the target range and sheet using Excel VBA.

Macro to copy the formulas from source range and paste into another range and sheet.

Sheets("AnotherSheet").Range("A1").PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False

CopyPaste Only the Border of a Range to Another Sheet in Excel VBA

The following macro will help us to copy and paste only the borders of the source range and ignore all other formats. We need this when you wants to maintain same border formats in all our target sheets.

Sheets("AnotherSheet").Range("A1").PasteSpecial Paste:=xlPasteAllExceptBorders, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False


Sheets("AnotherSheet").Range("A1").PasteSpecial Paste:=xlPasteAllExceptBorders, Operation:=xlNone, _
SkipBlanks:=True, Transpose:=True

Best Practices to follow while Copying Excel Range to another Sheet

Excel VBA macros are very helpfull to copy Excel Range to another sheet. We recommend you to note the below points while automating the copy paste tasks.

  • Clear the Target Range: Always clear the target  range (in Another sheet) before copying and pasting the data. There may be some data or formats avaialbe in the target range. This will make sure that you have same source data in the target sheet. And this will clear any pre formats and reduce the file size.
  • Specify Source and Destination Sheets: Try to specify both of the source and destination sheets. So that you can run your macro from any sheet. If your source range is alwas from active sheet, then do not specify the source sheet.
  • Do not perform any other operations between Copy and Paste. It is noticed many beginners copy the range and do some task and then pasting the values. Excel will turn off the CutCopy mode and no data will be pasted in your destination sheet.
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • How to Copy Range to Another Sheet with Formatting in Excel VBA
    • How to copy the Excel Range including Column widths
      • Method 1: Using PasteSpecial Method to Copy Range and Paste in Another Sheet with Formatting and Column Widths.
      • Method 3: Copying Entire Range of Columns and Paste in Another Sheet.
      • Method 3: Explicitly specifying the Column Widths
      • Copy Range Values to Another Sheet with out Formatting in Excel VBA
      • Copy Formats of a Range to Another Sheet using Excel VBA
      • Copy Formulas of a Range to Another Sheet using Excel VBA
      • CopyPaste Only the Border of a Range to Another Sheet in Excel VBA
    • Best Practices to follow while Copying Excel Range to another Sheet

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

One Comment

  1. Jo
    July 10, 2019 at 8:31 AM — Reply

    Clear and very helpful. Thanks for providing a the macro to copy ranges in Excel sheets.

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Содержание

  1. VBA copy cells value and format
  2. 4 Answers 4
  3. Linked
  4. Related
  5. Hot Network Questions
  6. Subscribe to RSS
  7. fast way to copy formatting in excel
  8. 5 Answers 5
  9. How can I copy Excel cells with rich text formatting but not the global cell format?
  10. How to Copy Cell Formatting to Another Range on Current/Another Worksheet in Excel
  11. Method 1: Copy Cell Formatting by Format Painter in Excel
  12. Method 2: Copy Cell Formatting by Excel VBA
  13. VBA Value Paste & PasteSpecial
  14. Paste Values
  15. Copy and Value Paste to Different Sheet
  16. Copy and Value Paste Ranges
  17. Copy and Value Paste Columns
  18. Copy and Value Paste Rows
  19. Paste Values and Number Formats
  20. VBA Coding Made Easy
  21. .Value instead of .Paste
  22. Cell Value vs. Value2 Property
  23. Copy Paste Builder
  24. Paste Special – Formats and Formulas
  25. Paste Formats
  26. Paste Formulas
  27. Paste Formulas and Number Formats
  28. Paste Special – Transpose and Skip Blanks
  29. Paste Special – Transpose
  30. Paste Special – Skip Blanks
  31. Other Paste Special Options
  32. Paste Special – Comments
  33. Paste Special – Validation
  34. Paste Special – All Using Source Theme
  35. Paste Special – All Except Borders
  36. PasteSpecial – Column Widths
  37. PasteSpecial – All MergingConditionalFormats
  38. VBA Code Examples Add-in

VBA copy cells value and format

How can I amend the following code in order to copy not only the value but also the fonts style, e.g. bold or not bold. Thanks

4 Answers 4

Instead of setting the value directly you can try using copy/paste, so instead of:

To just set the font to bold you can keep your existing assignment and add this:

It gives a bunch of options to customize how you paste. For instance, you could xlPasteAll (probably what you’re looking for), or xlPasteAllUsingSourceTheme, or even xlPasteAllExceptBorders.

Following on from jpw it might be good to encapsulate his solution in a small subroutine to save on having lots of lines of code:

(I do not have Excel in current location so please excuse bugs as not tested)

Found this on OzGrid courtesy of Mr. Aaron Blood — simple direct and works.

However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this.

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

fast way to copy formatting in excel

I have two bits of code. First a standard copy paste from cell A to cell B

I can do almost the same using

Now this second method is much faster, avoiding copying to clipboard and pasting again. However it does not copy across the formatting as the first method does. The Second version is almost instant to copy 500 lines, while the first method adds about 5 seconds to the time. And the final version could be upwards of 5000 cells.

So my question can the second line be altered to included the cell formatting (mainly font colour) while still staying fast.

Ideally I would like to be able to copy the cell values to a array/list along with the font formatting so I can do further sorting and operations on them before I «paste» them back on to the worksheet..

So my ideal solution would be some thing like

is it possible to use RTF strings in VBA or is that only possible in vb.net, etc.

Answer*

Just to see how my origianl method and new method compar, here are the results or before and after

New code = 65msec

Old code = 1296msec

5 Answers 5

You could have simply used Range(«x1»).value(11) something like below:

range has default property «Value» plus value can have 3 optional orguments 10,11,12. 11 is what you need to tansfer both value and formats. It doesn’t use clipboard so it is faster.- Durgesh

For me, you can’t. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:

And, by the way, you can build a custom range string, like Range(«B2:B4, B6, B11:B18»)

edit: if your source is «sparse», can’t you just format the destination at once when the copy is finished ?

Remember that when you write:

you are really writing

You can also use names:

But Value is not the only property of Range. I have used:

would work but I would expect

I do not know what formats you want to copy so you will have to try.

However, I must add that when you copy and paste a large range, it is not as much slower than doing it via an array as we all thought.

Post Edit information

Having posted the above I tried by own advice. My experiments with copying Font.Color and Font.Bold to an array have failed.

Of the following statements, the second would fail with a type mismatch:

ValueArray must be of type variant. I tried both variant and long for ColourArray without success.

I filled ColourArray with values and tried the following statement:

The entire range would be coloured according to the first element of ColourArray and then Excel looped consuming about 45% of the processor time until I terminated it with the Task Manager.

There is a time penalty associated with switching between worksheets but recent questions about macro duration have caused everyone to review our belief that working via arrays was substantially quicker.

I constructed an experiment that broadly reflects your requirement. I filled worksheet Time1 with 5000 rows of 20 cells which were selectively formatted as: bold, italic, underline, subscript, bordered, red, green, blue, brown, yellow and gray-80%.

With version 1, I copied every 7th cells from worksheet «Time1» to worksheet «Time2» using copy.

With version 2, I copied every 7th cells from worksheet «Time1» to worksheet «Time2» by copying the value and the colour via an array.

With version 3, I copied every 7th cells from worksheet «Time1» to worksheet «Time2» by copying the formula and the colour via an array.

Version 1 took an average of 12.43 seconds, version 2 took an average of 1.47 seconds while version 3 took an average of 1.83 seconds. Version 1 copied formulae and all formatting, version 2 copied values and colour while version 3 copied formulae and colour. With versions 1 and 2 you could add bold and italic, say, and still have some time in hand. However, I am not sure it would be worth the bother given that copying 21,300 values only takes 12 seconds.

** Code for Version 1**

I do not think this code includes anything that needs an explanation. Respond with a comment if I am wrong and I will fix.

** Code for Versions 2 and 3**

The User type definition must be placed before any subroutine in the module. The code works through the source worksheet copying values or formulae and colours to the next element of the array. Once selection has been completed, it copies the collected information to the destination worksheet. This avoids switching between worksheets more than is essential.

Источник

How can I copy Excel cells with rich text formatting but not the global cell format?

Using VBA, I’m copying the value of one cell to another:

This works fine, but if the source contains rich text formatting, the formatting is lost.

I could copy the entire cell, formats and all:

But this brings along not just rich text formatting, but also global formats on the cell — background color, borders, etc. I’m only interested in copying formats that apply to portions of the text (for example, one word in a sentence being in bold).

I’ve also tried copying the format of each character:

The actual code for the above includes italics, underlines, etc., and caches Characters() as an object for speed, but still, the performance is way too slow for production use.

The last option I can think of is to copy the cell with formatting, then undo any changes to background color or pattern, borders, font name/size, etc.:

This still seems kludgy, it’s difficult to save off all of the formats to be re-applied, and I can’t «undo» formatting like bold, italics, etc. that could either be applied at a cell or character level without erasing the character-level settings.

Any other options out there? The formatting in the Excel OpenOfficeXML file is stored with ranges of characters, but it doesn’t appear these formatted ranges are available via the API, at least as far as I can find.

Edit: Using KazJaw’s approach below, I was able to get what I needed with the following code:

This temporarily preserves the cell formatting of my destination cell in the last cell of the first row, copies the source with all formatting, pastes back the formatting in the temp cell, and finally also copies back the preserved overall font and size (which in my case I don’t want to copy over from the source). Finally, the temp cell is cleared so it doesn’t impact the worksheet dimensions.

It’s an imperfect solution, especially since it relies on the clipboard, but the performance is good and it does what it needs to do.

Источник

How to Copy Cell Formatting to Another Range on Current/Another Worksheet in Excel

Sometimes we want to copy cell format to others to make cells or tables in unique format. We can check the cell format and then set the same format for the cells you want to apply the formatting, but this way is very complex and boring. We need some way simple and convenient to apply. This article will provide you two methods to suit your requirement. The first one is using Format Painter, the second one is Excel VBA, it can automate copy cell format to others.

For example, we have a table formatting as below:

This table is combined with 3 rows and 3 columns, it has bold borders and different colors of background. If we want to create a table with this format or make existing table copy this format, we can use format painter, please see details below.

Method 1: Copy Cell Formatting by Format Painter in Excel

Step 1: Drag and select the range B2:D5 you want to copy the formatting.

Step 2: Click Home->Format Painter in ribbon.

Verify that the selected range is highlighted. And cursor is changed to a painter.

Step 3: Drag and select the range you want to apply with the formatting. For example, F2:H5.

Step 4: Release your mouse. Verify that a table with the same format is created.

Step 5: If table is already created with values but the format is not applied, after copy cell formatting by format painter, the table will be applied with formatting properly.

Before: After:

Method 2: Copy Cell Formatting by Excel VBA

  1. Below method is applied for copy cell with only formatting to another range on current sheet or another sheet.

Step 1: Right click on Sheet1 to load Sheet management menu. Select View Code, Microsoft Visual Basic for Applications window pops up.

Or you can enter Microsoft Visual Basic for Applications window via Developer->Visual Basic.

Step 2: In Microsoft Visual Basic for Applications window, click Insert->Module, enter below code in Module1:

Step 3: Save the codes, see screenshot below. And then quit Microsoft Visual Basic for Applications.

Step 4: On current sheet1, click Developer->Macro, in Macro window, select CopyCellFormatting Macro, then click Run.

Step 5: CopyCellFormat input box pops up. In Source textbox, enter the range you want to copy cell formatting with. Then click OK.

Step 6: In Destination textbox, enter the range you want to apply the formatting with. Then click OK.

Step 7: Verify that F8:H11 are applied with the formatting.

Step 8: You can also run macro on another sheet like sheet2 to copy and apply cell formatting on sheet2, just add sheet1 when enter source range.

  1. Below method is applied for copy cell with both value and formatting to another worksheet.

Step 1: Right click on Sheet1 to load Sheet management menu. Select View Code, Microsoft Visual Basic for Applications window pops up.

Or you can enter Microsoft Visual Basic for Applications window via Developer->Visual Basic.

Step 2: In Microsoft Visual Basic for Applications window, click Insert->Module, enter below code in Module1:

Step 3: Save the codes, see screenshot below. And then quit Microsoft Visual Basic for Applications.

Step 4: On sheet2, click Developer->Macro, in Macro window, select CopyCellValuesAndFormatting Macro, then click Run.

Step 5: Verify that table in sheet1 with values and formatting is copied to B2:D5 automatically in sheet2. You can clear the values in cells and re-enter your own data.

Comments:

  1. You can change Sheet and Range parameters to you owns to suit your requirement.
  2. This is only available for coping cell to another worksheet.

Источник

VBA Value Paste & PasteSpecial

In this Article

This tutorial will show you how to use PasteSpecial in VBA to paste only certain cell properties (exs. values, formats)

In Excel, when you copy and paste a cell you copy and paste all of the cell’s properties: values, formats, formulas, numberformatting, borders, etc:

Instead, you can “Paste Special” to only paste certain cell properties. In Excel, the Paste Special menu can be accessed with the shortcut CTRL + ALT + V (after copying a cell):

Here you can see all the combinations of cell properties that you can paste.

If you record a macro while using the Paste Special Menu, you can simply use the generated code. This is often the easiest way to use VBA to Paste Special.

Paste Values

Paste Values only pastes the cell “value”. If the cell contained a formula, Paste Values will paste the formula result.

This code will Copy & Paste Values for a single cell on the same worksheet:

Copy and Value Paste to Different Sheet

This example will Copy & Paste Values for single cells on different worksheets

These examples will Copy & Paste Values for a ranges of cells:

Copy and Value Paste Ranges

Copy and Value Paste Columns

Copy and Value Paste Rows

Paste Values and Number Formats

Pasting Values will only paste the cell value. No Formatting is pasted, including Number Formatting.

Often when you Paste Values you will probably want to include the number formatting as well so your values remain formatted. Let’s look at an example.

Here we will value paste a cell containing a percentage:

Notice how the percentage number formatting is lost and instead a sloppy decimal value is shown.

Instead let’s use Paste Values and Numbers formats:

Now you can see the number formatting is also pasted over, maintaining the percentage format.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

.Value instead of .Paste

Instead of Pasting Values, you could use the Value property of the Range object:

This will set A2’s cell value equal to B2’s cell value

You can also set a range of cells equal to a single cell’s value:

or a range of cells equal to another identically sized range of cells:

It’s less typing to use the Value property. Also, if you want to become proficient with Excel VBA, you should be familiar with working with the Value property of cells.

Cell Value vs. Value2 Property

Technically, it’s better to use the Value2 property of a cell. Value2 is slightly faster (this only matters with extremely large calculations) and the Value property might give you a truncated result of the cell is formatted as currency or a date. However, 99%+ of code that I’ve seen uses .Value and not .Value2. I personally do not use .Value2, but you should be aware that it exists.

Copy Paste Builder

We’ve created a “Copy Paste Code Builder” that makes it easy to generate VBA code to copy (or cut) and paste cells. The builder is part of our VBA Add-in: AutoMacro.

AutoMacro also contains many other Code Generators, an extensive Code Library, and powerful Coding Tools.

Paste Special – Formats and Formulas

Besides Paste Values, the most common Paste Special options are Paste Formats and Paste Formulas

Paste Formats

Paste formats allows you to paste all cell formatting.

Paste Formulas

Paste formulas will paste only the cell formulas. This is also extremely useful if you want to copy cell formulas, but don’t want to copy cell background colors (or other cell formatting).

Paste Formulas and Number Formats

Similar to Paste Values and Number Formats above, you can also copy and paste number formats along with formulas

Here we will copy a cell formula with Accounting Number Formatting and Paste Formulas only.

Notice how the number formatting is lost and instead a sloppy non-rounded value is shown instead.

Instead let’s use Paste Formulas and Numbers formats:

Now you can see the number formatting is also pasted over, maintaining the Accounting format.

Paste Special – Transpose and Skip Blanks

Paste Special – Transpose

Paste Special Transpose allows you to copy and paste cells changing the orientation from top-bottom to left-right (or vis-a-versa):

Paste Special – Skip Blanks

Skip blanks is a paste special option that doesn’t seem to be used as often as it should be. It allows you to copy only non-blank cells when copying and pasting. So blank cells are not copied.

In this example below. We will copy column A, do a regular paste in column B and skip blanks paste in column C. You can see the blank cells were not pasted into column C in the image below.

Other Paste Special Options

Paste Special – Validation

Paste Special – All Using Source Theme

Paste Special – All Except Borders

PasteSpecial – Column Widths

A personal favorite of mine. PasteSpecial Column Widths will copy and paste the width of columns.

PasteSpecial – All MergingConditionalFormats

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

RRS feed

  • Remove From My Forums
  • Question

  • Can anyone help work out how to copy the format (column width, colour,…) from a range in one Excel .xls to an equal range in another .xls.  Currently using the following format

    Worksheets(«file1.xls!sheet»).Range(«A1:IL36»).Copy _
            Destination:=Worksheets(«file2.xls!sheet»).Range(«A1:IL36»)

    Works among sheets within one .xls but does not copy format, only contents

    r.con

All replies

  • To copy the column widths I think you need to copy the entire column and then select the entire column in the destination workbook and do a PasteSpecial.

    Something like

    Sub Test()

    ‘copies the range and its formats
    Workbooks(«Source.xls»).Sheets(«Sheet1»).Range(«A1:C40»).Copy
    Workbooks(«Destination.xls»).Sheets(«Sheet1»).Range(«A1:C40»).PasteSpecial (xlPasteAll)

    ‘copies the column widths and their formats
    Workbooks(«Source.xls»).Sheets(«Sheet1»).Range(«A:C»).Copy
    Workbooks(«Destination.xls»).Sheets(«Sheet1»).Range(«A:C»).PasteSpecial (xlPasteFormats)

    End Sub

    • Proposed as answer by

      Saturday, July 14, 2012 10:39 PM

  • Thanks very much,

         The code seems right but now I get my old error of «Run-time error ‘9’: Subscript out of range».  I have used other code to attempt the same function with the same results.

    Rodcon

  • In your code you refer to workbooks and sheets in a way I have not seen.

    Try:

    Workbooks(«Source.xls»).Sheets(«Sheet1»)…

    Make sure you include the .xls after the filename or you can get errors.

Если вы хотите скопировать только форматирование ячейки из диапазона, как это сделать быстро? В этом руководстве представлены быстрые сокращения, позволяющие легко копировать только форматирование.

Копирование форматирования только с помощью Format Painter в Excel

Копировать форматирование только с помощью VBA

Копировать форматирование только с Kutools for Excel хорошая идея3


Копирование форматирования только с помощью Format Painter в Excel

В Excel вы можете копировать форматирование ячеек только с помощью Формат Painter инструмент.

1. Выберите диапазон, содержащий формат ячеек, который вы хотите скопировать. Смотрите скриншот:

2. Применение Формат Painter щелкнув его под Главная вкладку, см. снимок экрана:

3. Выберите пустую ячейку и щелкните по ней, будет вставлено только форматирование ячеек. Смотрите скриншот:

Внимание: Формат Painter также можно копировать форматирование только на другой лист.


Копировать форматирование только с помощью VBA

Следующие макросы также могут помочь вам скопировать только форматирование ячеек.

1. Держать ALT и нажмите F11 на клавиатуре, чтобы открыть Microsoft Visual Basic для приложений окно.

2. Нажмите Вставить > Модули, и скопируйте VBA в модуль.

VBA: копировать только форматирование ячеек:

Sub CopyFormat()
'Update 20130815
Dim CopyRng As Range, PasteRng As Range
xTitleId = "KutoolsforExcel"
Set CopyRng = Application.Selection
Set CopyRng = Application.InputBox("Ranges to be copied :", xTitleId, CopyRng.Address, Type:=8)
Set PasteRng = Application.InputBox("Paste to (single cell):", xTitleId, Type:=8)
CopyRng.Copy
PasteRng.Parent.Activate
PasteRng.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub

3. Нажмите Run или нажмите F5 для запуска VBA. На экране отображается диалоговое окно, и вы должны выбрать ячейки, форматирование которых вы хотите скопировать. Смотрите скриншот:

4. Нажмите Ok и другое диалоговое окно отображается для вас, чтобы выбрать ячейку для вставки форматирования. Смотрите скриншот:

6. Нажмите Ok, то форматирование ячеек вставляется в выбранную ячейку. Смотрите скриншот:

 Внимание: С помощью этого кода VBA вы можете вставлять только форматирование в другие рабочие листы, которые вы хотите.


Копировать форматирование только с Kutools for Excel

Есть Kutools for Excel установлен, Копировать диапазоны Функция может помочь вам быстро и легко скопировать только форматирование ячеек.

После установки Kutools for Excel, пожалуйста, сделайте, как показано ниже :( Бесплатная загрузка Kutools for Excel Сейчас!)

Пожалуйста, примените Копировать диапазоны функция, нажав Кутулс > Копировать диапазоны. Смотрите скриншот:

только документ копировать форматирование 9

1. Выделите ячейки, форматирование которых вы хотите скопировать.

2. Нажмите Кутулс > Копировать диапазонs, на экране появится диалог, отметьте Форматы вариант под Специальная вставка, см. снимок экрана:

3. И нажмите ОК. Другой диалог отображается для вас, чтобы выбрать ячейку для вставки результата. Смотрите скриншот:

4. Нажмите Ok, и в выбранную ячейку вставляется только форматирование. Смотрите скриншот:

Внимание: Вы также можете копировать и вставлять форматирование ячеек между двумя электронными таблицами. Если вы хотите скопировать высоту строки и ширину столбца, вы можете проверить Включая высоту строки и Включая ширину столбца коробка в Копировать несколько диапазонов Диалог.

Работы С Нами Kutools for ExcelКопировать диапазоны, вы также можете копировать только значения, формулы или комментарии.

Наконечник.Если вы хотите подсчитать или суммировать ячейки на основе цветов, попробуйте использовать Kutools for ExcelАвтора Считать по цвету как показано на следующем снимке экрана. Полная функция без ограничений в 30 дней, пожалуйста, скачайте и получите бесплатную пробную версию сейчас.

Считать по цвету

В некоторых случаях у вас может быть диапазон значений с несколькими цветами, и вы хотите подсчитывать / суммировать значения на основе одного и того же цвета, как вы можете быстро рассчитать?
Работы С Нами Kutools for Excel‘s Считать по цвету, вы можете быстро выполнить множество вычислений по цвету, а также можете сформировать отчет о рассчитанном результате.

количество документов по цвету


Относительные статьи:

  • Копировать числа без формул в ячейки
  • Копировать только комментарии из ячеек в другую
  • Копировать значения и форматирование в ячейки

Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

In this Article

  • Paste Values
    • Copy and Value Paste to Different Sheet
    • Copy and Value Paste Ranges
    • Copy and Value Paste Columns
    • Copy and Value Paste Rows
    • Paste Values and Number Formats
    • .Value instead of .Paste
    • Cell Value vs. Value2 Property
    • Copy Paste Builder
  • Paste Special – Formats and Formulas
    • Paste Formats
    • Paste Formulas
    • Paste Formulas and Number Formats
  • Paste Special – Transpose and Skip Blanks
    • Paste Special – Transpose
    • Paste Special – Skip Blanks
  • Other Paste Special Options
    • Paste Special – Comments
    • Paste Special – Validation
    • Paste Special – All Using Source Theme
    • Paste Special – All Except Borders
    • PasteSpecial – Column Widths
    • PasteSpecial – All MergingConditionalFormats

This tutorial will show you how to use PasteSpecial in VBA to paste only certain cell properties (exs. values, formats)

In Excel, when you copy and paste a cell you copy and paste all of the cell’s properties: values, formats, formulas, numberformatting, borders, etc:

vba copy paste special

Instead, you can “Paste Special” to only paste certain cell properties. In Excel, the Paste Special menu can be accessed with the shortcut CTRL + ALT + V (after copying a cell):

paste special vba

Here you can see all the combinations of cell properties that you can paste.

If you record a macro while using the Paste Special Menu, you can simply use the generated code. This is often the easiest way to use VBA to Paste Special.

Paste Values

Paste Values only pastes the cell “value”. If the cell contained a formula, Paste Values will paste the formula result.

This code will Copy & Paste Values for a single cell on the same worksheet:

Range("A1").Copy
Range("B1").PasteSpecial Paste:=xlPasteValues

Copy and Value Paste to Different Sheet

This example will Copy & Paste Values for single cells on different worksheets

Sheets("Sheet1").Range("A1").Copy
Sheets("Sheet2").Range("B1").PasteSpecial Paste:=xlPasteValues

These examples will Copy & Paste Values for a ranges of cells:

Copy and Value Paste Ranges

Range("A1:B3").Copy
Range("C1").PasteSpecial Paste:=xlPasteValues

Copy and Value Paste Columns

Columns("A").Copy
Columns("B").PasteSpecial Paste:=xlPasteValues

Copy and Value Paste Rows

Rows(1).Copy
Rows(2).PasteSpecial Paste:=xlPasteValues

Paste Values and Number Formats

Pasting Values will only paste the cell value. No Formatting is pasted, including Number Formatting.

Often when you Paste Values you will probably want to include the number formatting as well so your values remain formatted. Let’s look at an example.

Here we will value paste a cell containing a percentage:

vba paste values number formats

Sheets("Sheet1").Columns("D").Copy
Sheets("Sheet2").Columns("B").PasteSpecial Paste:=xlPasteValues

vba paste values

Notice how the percentage number formatting is lost and instead a sloppy decimal value is shown.

Instead let’s use Paste Values and Numbers formats:

Sheets("Sheet1").Columns("D").Copy
Sheets("Sheet2").Columns("B").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

vba paste special values number formats

Now you can see the number formatting is also pasted over, maintaining the percentage format.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

.Value instead of .Paste

Instead of Pasting Values, you could use the Value property of the Range object:

This will set A2’s cell value equal to B2’s cell value

Range("A2").Value = Range("B2").Value

You can also set a range of cells equal to a single cell’s value:

Range("A2:C5").Value = Range("A1").Value

or a range of cells equal to another identically sized range of cells:

Range("B2:D4").Value = Range("A1:C3").Value

It’s less typing to use the Value property. Also, if you want to become proficient with Excel VBA, you should be familiar with working with the Value property of cells.

Cell Value vs. Value2 Property

Technically, it’s better to use the Value2 property of a cell. Value2 is slightly faster (this only matters with extremely large calculations) and the Value property might give you a truncated result of the cell is formatted as currency or a date.  However, 99%+ of code that I’ve seen uses .Value and not .Value2.  I personally do not use .Value2, but you should be aware that it exists.

Range("A2").Value2 = Range("B2").Value2

Copy Paste Builder

We’ve created a “Copy Paste Code Builder” that makes it easy to generate VBA code to copy (or cut) and paste cells. The builder is part of our VBA Add-in: AutoMacro.

vba copy paste helper

AutoMacro also contains many other Code Generators, an extensive Code Library, and powerful Coding Tools.

VBA Programming | Code Generator does work for you!

Paste Special – Formats and Formulas

Besides Paste Values, the most common Paste Special options are Paste Formats and Paste Formulas

Paste Formats

Paste formats allows you to paste all cell formatting.

Range("A1:A10").Copy
Range("B1:B10").PasteSpecial Paste:=xlPasteFormats

Paste Formulas

Paste formulas will paste only the cell formulas. This is also extremely useful if you want to copy cell formulas, but don’t want to copy cell background colors (or other cell formatting).

Range("A1:A10").Copy
Range("B1:B10").PasteSpecial Paste:=xlPasteFormulas

Paste Formulas and Number Formats

Similar to Paste Values and Number Formats above, you can also copy and paste number formats along with formulas

vba paste special formulas

Here we will copy a cell formula with Accounting Number Formatting and Paste Formulas only.

Sheets("Sheet1").Range("D3").Copy
Sheets("Sheet2").Range("D3").PasteSpecial xlPasteFormulas

vba paste special formulas formats

Notice how the number formatting is lost and instead a sloppy non-rounded value is shown instead.

Instead let’s use Paste Formulas and Numbers formats:

Sheets("Sheet1").Range("D3").Copy
Sheets("Sheet2").Range("D3").PasteSpecial xlPasteFormulasAndNumberFormats

vba paste special formulas numberformatting

Now you can see the number formatting is also pasted over, maintaining the Accounting format.

Paste Special – Transpose and Skip Blanks

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Paste Special – Transpose

Paste Special Transpose allows you to copy and paste cells changing the orientation from top-bottom to left-right (or vis-a-versa):

Sheets("Sheet1").Range("A1:A5").Copy
Sheets("Sheet1").Range("B1").PasteSpecial Transpose:=True

vba paste special transpose

vba transpose

Paste Special – Skip Blanks

Skip blanks is a paste special option that doesn’t seem to be used as often as it should be.  It allows you to copy only non-blank cells when copying and pasting. So blank cells are not copied.

In this example below. We will copy column A, do a regular paste in column B and skip blanks paste in column C. You can see the blank cells were not pasted into column C in the image below.

Sheets("Sheet1").Range("A1:A5").Copy
Sheets("Sheet1").Range("B1").PasteSpecial SkipBlanks:=False
Sheets("Sheet1").Range("C1").PasteSpecial SkipBlanks:=True

vba value paste skip blanks

vba skip blanks

Other Paste Special Options

Sheets("Sheet1").Range("A1").Copy Sheets("Sheet1").Range("E1").PasteSpecial xlPasteComments

vba paste special comments

vba paste comments

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Paste Special – Validation

vba paste special validation

Sheets("Sheet1").Range("A1:A4").Copy
Sheets("Sheet1").Range("B1:B4").PasteSpecial xlPasteValidation

vba paste validation

Paste Special – All Using Source Theme

vba paste special allusingsourcetheme

Workbooks(1).Sheets("Sheet1").Range("A1:A2").Copy
Workbooks(2).Sheets("Sheet1").Range("A1").PasteSpecial
Workbooks(2).Sheets("Sheet1").Range("B1").PasteSpecial xlPasteAllUsingSourceTheme

Paste Special – All Except Borders

Range("B2:C3").Copy
Range("E2").PasteSpecial
Range("H2").PasteSpecial xlPasteAllExceptBorders

vba paste special allexceptborders

PasteSpecial – Column Widths

A personal favorite of mine. PasteSpecial Column Widths will copy and paste the width of columns.

Range("A1:A2").Copy
Range("C1").PasteSpecial
Range("E1").PasteSpecial xlPasteColumnWidths

vba paste special column widths

PasteSpecial – All MergingConditionalFormats

vba paste special all merging conditional formats

Range("A1:A4").Copy
Range("C1").PasteSpecial
Range("E1").PasteSpecial xlPasteAllMergingConditionalFormats

vba paste special formats

Sometimes we want to copy cell format to others to make cells or tables in unique format. We can check the cell format and then set the same format for the cells you want to apply the formatting, but this way is very complex and boring. We need some way simple and convenient to apply. This article will provide you two methods to suit your requirement. The first one is using Format Painter, the second one is Excel VBA, it can automate copy cell format to others.

For example, we have a table formatting as below:

Copy Cell Formatting to Another Range 1

This table is combined with 3 rows and 3 columns, it has bold borders and different colors of background. If we want to create a table with this format or make existing table copy this format, we can use format painter, please see details below.

Method 1: Copy Cell Formatting by Format Painter in Excel


Step 1: Drag and select the range B2:D5 you want to copy the formatting.

Copy Cell Formatting to Another Range 2

Step 2: Click Home->Format Painter in ribbon.

Copy Cell Formatting to Another Range 3

Verify that the selected range is highlighted. And cursor is changed to a painter.

Copy Cell Formatting to Another Range 4

Step 3: Drag and select the range you want to apply with the formatting. For example, F2:H5.

Step 4: Release your mouse. Verify that a table with the same format is created.

Copy Cell Formatting to Another Range 5

Step 5: If table is already created with values but the format is not applied, after copy cell formatting by format painter, the table will be applied with formatting properly.

Before:                                                                                          After:

Copy Cell Formatting to Another Range 6                           Copy Cell Formatting to Another Range 7

 Method 2: Copy Cell Formatting by Excel VBA


  1. Below method is applied for copy cell with only formatting to another range on current sheet or another sheet.

Step 1: Right click on Sheet1 to load Sheet management menu. Select View Code, Microsoft Visual Basic for Applications window pops up.

Or you can enter Microsoft Visual Basic for Applications window via Developer->Visual Basic.

Step 2: In Microsoft Visual Basic for Applications window, click Insert->Module, enter below code in Module1:

Sub CopyCellFormating()

Dim CopyRng As Range, PasteRng As Range

xTitleId = "CopyCellFormating"

Set CopyRng = Application.Selection

Set CopyRng = Application.InputBox("Source:", xTitleId, CopyRng.Address, Type:=8)

Set PasteRng = Application.InputBox("Destination:", xTitleId, Type:=8)

CopyRng.Copy

PasteRng.Parent.Activate

PasteRng.PasteSpecial xlPasteFormats

Application.CutCopyMode = False

End Sub

Step 3: Save the codes, see screenshot below. And then quit Microsoft Visual Basic for Applications.

Copy Cell Formatting to Another Range 8

Step 4: On current sheet1, click Developer->Macro, in Macro window, select CopyCellFormatting Macro, then click Run.

Copy Cell Formatting to Another Range 9

Step 5: CopyCellFormat input box pops up. In Source textbox, enter the range you want to copy cell formatting with. Then click OK.

Copy Cell Formatting to Another Range 10

Step 6: In Destination textbox, enter the range you want to apply the formatting with. Then click OK.

Copy Cell Formatting to Another Range 11

Step 7: Verify that F8:H11 are applied with the formatting.

Copy Cell Formatting to Another Range 12

Step 8: You can also run macro on another sheet like sheet2 to copy and apply cell formatting on sheet2, just add sheet1 when enter source range.

Copy Cell Formatting to Another Range 13

  1. Below method is applied for copy cell with both value and formatting to another worksheet.

Step 1: Right click on Sheet1 to load Sheet management menu. Select View Code, Microsoft Visual Basic for Applications window pops up.

Or you can enter Microsoft Visual Basic for Applications window via Developer->Visual Basic.

Step 2: In Microsoft Visual Basic for Applications window, click Insert->Module, enter below code in Module1:

Sub CopyCellValuesAndFormatting()

Sheets("Sheet1").Range("B2:D5").Copy Destination:=Sheets("Sheet2").Range("B2:D5")

End Sub

Step 3: Save the codes, see screenshot below. And then quit Microsoft Visual Basic for Applications.

Copy Cell Formatting to Another Range 14

Step 4: On sheet2, click Developer->Macro, in Macro window, select CopyCellValuesAndFormatting Macro, then click Run.

Copy Cell Formatting to Another Range 15

Step 5: Verify that table in sheet1 with values and formatting is copied to B2:D5 automatically in sheet2. You can clear the values in cells and re-enter your own data.

Comments:

  1. You can change Sheet and Range parameters to you owns to suit your requirement.
  2. This is only available for coping cell to another worksheet.

  • #2

Just copy it with VBA and then use this line:

Code:

Range("yourRangeHere").FormatConditions.Delete

So like if you want to copy A1:A10 to C1:C10 you could write:

Code:

Range("A1:A10").Copy Range("C1")
Range("C1:C10").FormatConditions.Delete

  • #3

This delete the formatting. I want to keep formatting but remove conditional rules to the newly pasted range.

  • #4

This only deletes formatting that is coming from Conditional Formatting rules. Are you saying you have a range that uses conditional formatting, and you want to copy it to another range, KEEP the formats, but delete the RULES?

RoryA

RoryA

MrExcel MVP, Moderator


  • #5

I think you’d need API calls. Something like this will paste the copied formatted data but without the rules:

Code:

Private Declare Function OpenClipboard Lib "user32.dll" (ByVal hwnd As Long) As Long
Private Declare Function CloseClipboard Lib "user32.dll" () As Long
Private Declare Function EnumClipboardFormats Lib "user32" (ByVal wFormat As Long) As Long
Private Declare Function GetClipboardFormatName Lib "user32" Alias "GetClipboardFormatNameA" ( _
                                                ByVal wFormat As Long, ByVal lpString As String, _
                                                ByVal nMaxCount As Long) As Long

Private Declare Function SetClipboardData Lib "user32" (ByVal wFormat As Long, ByVal hMem As Long) As Long
Private Declare Function GetClipboardData Lib "user32.dll" (ByVal wFormat As Long) As Long
Private Declare Function GlobalLock Lib "kernel32.dll" (ByVal hMem As Long) As Long
Private Declare Function GlobalUnlock Lib "kernel32.dll" (ByVal hMem As Long) As Long
Private Declare Function lstrlen Lib "kernel32.dll" Alias "lstrlenA" ( _
                                 ByVal lpString As Long) As Long
Private Declare Function lstrcpy Lib "kernel32.dll" ( _
                                 ByVal lpStr1 As Any, ByVal lpStr2 As Any) As Long

Sub PasteAsLocalFormula()
'If the clipbaord contains an Excel range, any formula is pasted unchanged, moving sheet and _
  cell references to the destination workbook.
    Dim S                     As String
    Dim i As Long, CF_Format  As Long
    Dim SaveDisplayAlerts As Boolean, SaveScreenUpdating As Boolean
    Dim HTMLInClipBoard       As Boolean
    Dim Handle As Long, Ptr As Long, FileName As String

    'Enumerate the clipboard formats
    If OpenClipboard(0) Then
        CF_Format = EnumClipboardFormats(0&)
        Do While CF_Format <> 0
            S = String(255, vbNullChar)
            i = GetClipboardFormatName(CF_Format, S, 255)
            S = Left(S, i)
            HTMLInClipBoard = InStr(1, S, "HTML Format", vbTextCompare) > 0

            If HTMLInClipBoard Then
                Handle = GetClipboardData(CF_Format)
                Ptr = GlobalLock(Handle)
                Application.CutCopyMode = False
                S = Space$(lstrlen(ByVal Ptr))
                lstrcpy S, ByVal Ptr
                GlobalUnlock Ptr
                SetClipboardData CF_Format, Handle
                ActiveSheet.PasteSpecial Format:="HTML"
                Exit Do
            End If

            CF_Format = EnumClipboardFormats(CF_Format)
        Loop
        CloseClipboard
    End If

End Sub

  • #6

Thanks Rorya :) that work great.

Now is there any easy way to use this during my Loops ? I loop thought different sheet to copy my data then go to Data sheet to paste it .

Anyway to make your code as Function so I can call it to paste or another easy way without putting 50 time the same for code.

Here is an extract of my code to show how I am currently pasting my data (Note I was using value to avoid copying Conditional formatting rules) :

Code:

ActiveSheet.Range("A" & foundS.Row + 1 & ":H" & foundEnd.Row - 1).Copy
                Sheets("Data").Range("A" & Rng).PasteSpecial Paste:=xlPasteValues

  • #7

@ Rory
Neat workaround … I had nevetr paid attention to the Worksheet.PasteSpecial Format argument

One thing I don’t understand is the need to set the CutCopyMode Property of the application to False (or to any onther Long value for that matter) in order for the code to work !!

Also, I don’t understand the need for copying the clipboard HTML content to a String buffer .. seems redundant to me unless I am missing something.

The folllowing simplification should work just as well :

Code:

    If OpenClipboard(0) Then
        CF_Format = EnumClipboardFormats(0&)
        Do While CF_Format <> 0
            S = String(255, vbNullChar)
            i = GetClipboardFormatName(CF_Format, S, 255)
            S = Left(S, i)
            HTMLInClipBoard = InStr(1, S, "HTML Format", vbTextCompare) > 0
            If HTMLInClipBoard Then
                Application.CutCopyMode = False
                ActiveSheet.PasteSpecial Format:="HTML"
                Exit Do
            End If
            CF_Format = EnumClipboardFormats(CF_Format)
        Loop
        CloseClipboard
    End If

Thanks for teaching us something new

Last edited: Aug 19, 2016

RoryA

RoryA

MrExcel MVP, Moderator


  • #8

@Jaafar,

I confess I wrote this so long ago I can’t remember why it is the way it is, but I suspect it was adapted quickly from something else (I think the routine name and the comment support this), which may explain the buffer.

I don’t think I ever figured out why you had to turn copy mode off for the code to work properly.

RoryA

RoryA

MrExcel MVP, Moderator


  • #9

Thanks Rorya :) that work great.

Now is there any easy way to use this during my Loops ?

Change the routine to:

Code:

Sub PasteFormattedRange(rgFrom as Range, rgTo as range)

    Dim S                     As String
    Dim rgStart as Range
    Dim i As Long, CF_Format  As Long
    Dim SaveDisplayAlerts As Boolean, SaveScreenUpdating As Boolean
    Dim HTMLInClipBoard       As Boolean
    Dim Handle As Long, Ptr As Long, FileName As String
set rgStart = selection
rgFrom.Copy

    'Enumerate the clipboard formats
    If OpenClipboard(0) Then
        CF_Format = EnumClipboardFormats(0&)
        Do While CF_Format <> 0
            S = String(255, vbNullChar)
            i = GetClipboardFormatName(CF_Format, S, 255)
            S = Left(S, i)
            HTMLInClipBoard = InStr(1, S, "HTML Format", vbTextCompare) > 0
            If HTMLInClipBoard Then
                Application.CutCopyMode = False
                Application.Goto rgTo
                ActiveSheet.PasteSpecial Format:="HTML"
                application.goto rgStart
                Exit Do
            End If
            CF_Format = EnumClipboardFormats(CF_Format)
        Loop
        CloseClipboard
    End If

End Sub

and then your code would become:

Code:

PasteFormattedRange ActiveSheet.Range("A" & foundS.Row + 1 & ":H" & foundEnd.Row - 1), Sheets("Data").Range("A" & Rng)

Last edited: Aug 19, 2016

  • #10

@Jaafar,

I confess I wrote this so long ago I can’t remember why it is the way it is, but I suspect it was adapted quickly from something else (I think the routine name and the comment support this), which may explain the buffer.

I don’t think I ever figured out why you had to turn copy mode off for the code to work properly.

Thanks

.Tima

5 / 5 / 0

Регистрация: 21.09.2012

Сообщений: 37

1

Скопировать содержимое ячейки с форматированием

03.03.2014, 13:10. Показов 8190. Ответов 9

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Как скопировать содержимое ячейки с форматированием на visual basic в excel?
Операция

Visual Basic
1
myS.Range(Ch & i) = mySE.Range(Ch & j)

или

Visual Basic
1
myS.Range(Ch & i).copy mySE.Range(Ch & j)

копирует только содержимое без форматирования.



0



Апострофф

Заблокирован

03.03.2014, 13:19

2

Цитата
Сообщение от .Tima
Посмотреть сообщение

Visual Basic
1
myS.Range(Ch & i).copy mySE.Range(Ch & j)

копирует с форматированием



1



15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

03.03.2014, 13:19

3

Лучший ответ Сообщение было отмечено .Tima как решение

Решение

Второе как раз с форматированием, кроме ширины столбца и высоты строки. i -> j. А первое j -> i, может в этом загвоздка.



1



mc-black

2784 / 716 / 106

Регистрация: 04.02.2011

Сообщений: 1,443

03.03.2014, 13:25

4

Второй вариант копирует и вставляет с форматированием. Если в диапазоне только одна ячейка, адресовать её удобней так:

Visual Basic
1
myS.Cells(srcRow, srcColumn).Copy mySE.Cells(dstRow, dstColumn)

где srcRow, dstRow — номер строки для ячейки, а srcColumn, dstColumn — номер столбца (в режиме показа ссылок R1C1).

P.S. С ответом опоздал



1



5 / 5 / 0

Регистрация: 21.09.2012

Сообщений: 37

03.03.2014, 14:12

 [ТС]

5

Цитата
Сообщение от Казанский
Посмотреть сообщение

Второе как раз с форматированием, кроме ширины столбца и высоты строки. i -> j. А первое j -> i, может в этом загвоздка.

Так и было, спасибо всем за помощь!

Цитата
Сообщение от mc-black
Посмотреть сообщение

Если в диапазоне только одна ячейка, адресовать её удобней так:

У меня адрес ячейки формируется из буквы и цифры, и как я понял, в данном случае можно лишь так:
myS.Range(Ch & i)
или можно иняче?



0



KoGG

5590 / 1580 / 406

Регистрация: 23.12.2010

Сообщений: 2,366

Записей в блоге: 1

03.03.2014, 15:07

6

Visual Basic
1
myS.Cells(i, Ch).Copy mySE.Cells(j, Ch)



1



5 / 5 / 0

Регистрация: 21.09.2012

Сообщений: 37

07.03.2014, 00:29

 [ТС]

7

Код

myS.Range(Ch & i).copy mySE.Range(Ch & j)

Копирует содержимое ячейки «формулой», а нужно «значением». Как быть?



0



KoGG

5590 / 1580 / 406

Регистрация: 23.12.2010

Сообщений: 2,366

Записей в блоге: 1

07.03.2014, 12:38

8

Visual Basic
1
 mySE.Range(Ch & j)=myS.Range(Ch & i)



1



5 / 5 / 0

Регистрация: 21.09.2012

Сообщений: 37

07.03.2014, 13:09

 [ТС]

9

Цитата
Сообщение от KoGG
Посмотреть сообщение

mySE.Range(Ch & j)=myS.Range(Ch & i)

Логично, но тогда не копируется форматирование.

Как я понимаю, для того, чтобы скопировать содержимое «значением» с форматированием нужно выполнить две операции:

Код

myS.Range(Ch & i).copy mySE.Range(Ch & j)
mySE.Range(Ch & j)=myS.Range(Ch & i)

Мысль в верном направлении?



0



KoGG

5590 / 1580 / 406

Регистрация: 23.12.2010

Сообщений: 2,366

Записей в блоге: 1

07.03.2014, 20:30

10

Можно так, либо эдак:

Visual Basic
1
2
myS.Range(Ch & i).Copy
mySE.Range(Ch & j).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False



2



Понравилась статья? Поделить с друзьями:
  • Vba combobox list from excel
  • Vba coding with excel
  • Vba codes for excel
  • Vba code with excel
  • Vba code for word