Copy range excel macro

Вырезание, перемещение, копирование и вставка ячеек (диапазонов) в VBA Excel. Методы Cut, Copy и PasteSpecial объекта Range, метод Paste объекта Worksheet.

Метод Range.Cut

Range.Cut – это метод, который вырезает объект Range (диапазон ячеек) в буфер обмена или перемещает его в указанное место на рабочем листе.

Синтаксис

Параметры

Параметры Описание
Destination Необязательный параметр. Диапазон ячеек рабочего листа, в который будет вставлен (перемещен) вырезанный объект Range (достаточно указать верхнюю левую ячейку диапазона). Если этот параметр опущен, объект вырезается в буфер обмена.

Для вставки на рабочий лист диапазона ячеек, вырезанного в буфер обмена методом Range.Cut, следует использовать метод Worksheet.Paste.

Метод Range.Copy

Range.Copy – это метод, который копирует объект Range (диапазон ячеек) в буфер обмена или в указанное место на рабочем листе.

Синтаксис

Параметры

Параметры Описание
Destination Необязательный параметр. Диапазон ячеек рабочего листа, в который будет вставлен скопированный объект Range (достаточно указать верхнюю левую ячейку диапазона). Если этот параметр опущен, объект копируется в буфер обмена.

Метод Worksheet.Paste

Worksheet.Paste – это метод, который вставляет содержимое буфера обмена на рабочий лист.

Синтаксис

Worksheet.Paste (Destination, Link)

Метод Worksheet.Paste работает как с диапазонами ячеек, вырезанными в буфер обмена методом Range.Cut, так и скопированными в буфер обмена методом Range.Copy.

Параметры

Параметры Описание
Destination Необязательный параметр. Диапазон (ячейка), указывающий место вставки содержимого буфера обмена. Если этот параметр не указан, используется текущий выделенный объект.
Link Необязательный параметр. Булево значение, которое указывает, устанавливать ли ссылку на источник вставленных данных: True – устанавливать, False – не устанавливать (значение по умолчанию).

В выражении с методом Worksheet.Paste можно указать только один из параметров: или Destination, или Link.

Для вставки из буфера обмена отдельных компонентов скопированных ячеек (значения, форматы, примечания и т.д.), а также для проведения транспонирования и вычислений, используйте метод Range.PasteSpecial (специальная вставка).

Примеры

Вырезание и вставка диапазона одной строкой (перемещение):

Range(«A1:C3»).Cut Range(«E1»)

Вырезание ячеек в буфер обмена и вставка методом ActiveSheet.Paste:

Range(«A1:C3»).Cut

ActiveSheet.Paste Range(«E1»)

Копирование и вставка диапазона одной строкой:

Range(«A18:C20»).Copy Range(«E18»)

Копирование ячеек в буфер обмена и вставка методом ActiveSheet.Paste:

Range(«A18:C20»).Copy

ActiveSheet.Paste Range(«E18»)

Копирование одной ячейки и вставка ее данных во все ячейки заданного диапазона:

Range(«A1»).Copy Range(«B1:D10»)


Skip to content

На чтение 2 мин. Просмотров 9.2k.

Что делает макрос: Этот макрос сможет копировать значения указанного диапазон данных и вставить их в новый диапазон.

Содержание

  1. Как макрос работает
  2. Код макроса
  3. Как использовать

Как макрос работает

В этом макросе, мы используем метод Copy объекта Range, чтобы скопировать данные из D6: D17 и вставить в L6: L17. Обратите внимание на использование целевого аргумента. Этот аргумент говорит Excel, где нужно вставить данные.

Код макроса

Sub KopirovanieDannih()
'Копируем данные
Sheets("Лист1").Range("D6:D17").Copy _
'Вставляем данные
Destination:=Sheets("Лист1").Range("L6:L17")
End Sub

При работе с таблицей, иногда приходится копировать формулы и вставлять их в качестве значений. Для этого в макросе, вы можете использовать метод PasteSpecial. В этом примере мы копируем формулы F6:F17 в M6:M17. Обратите внимание на то, что мы не только используем xlPasteValues, также xlPasteFormats, чтобы применить форматирование из скопированного диапазона.

Sub KopirovanieDannihIFormata()
Sheets("Лист1").Range("F6:F17").Copy
Sheets("Лист1").Range("M6:M17").PasteSpecial xlPasteValues
Sheets("Лист1").Range("M6:M17").PasteSpecial xlPasteFormats
End Sub

Как использовать

Для реализации этого макроса, вы можете скопировать и вставить его в стандартный модуль:

  1. Активируйте редактор Visual Basic, нажав ALT + F11 на клавиатуре.
  2. Щелкните правой кнопкой мыши имя проекта / рабочей книги в окне проекта.
  3. Выберите Insert➜Module.
  4. Введите или вставьте код.

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

Go to Top

Bottom line: Learn 3 different ways to copy and paste cells or ranges in Excel with VBA Macros.  This is a 3-part video series and you can also download the file that contains the code.

Skill level: Beginner

3 Ways to Copy and Paste in Excel with VBA Macros

Copy & Paste: The Most Common Excel Action

Copy and paste is probably one of the most common actions you take in Excel.  It’s also one of the most common tasks we automate when writing macros.

There are a few different ways to accomplish this task, and the macro recorder doesn’t always give you the most efficient VBA code.

In the following three videos I explain:

  • The most efficient method for a simple copy and paste in VBA.
  • The easiest way to paste values.
  • How to use the PasteSpecial method for other paste types.

You can download the file I use in these videos below.  The code is also available at the bottom of the page.

Video #1: The Simple Copy Paste Method

You can watch the playlist that includes all 3 videos at the top of this page.

Video #2: An Easy Way to Paste Values

Video #3: The PasteSpecial Method Explained

VBA Code for the Copy & Paste Methods

Download the workbook that contains the code.

'3 Methods to Copy & Paste with VBA
'Source: https://www.excelcampus.com/vba/copy-paste-cells-vba-macros/
'Author: Jon Acampora

Sub Range_Copy_Examples()
'Use the Range.Copy method for a simple copy/paste

    'The Range.Copy Method - Copy & Paste with 1 line
    Range("A1").Copy Range("C1")
    Range("A1:A3").Copy Range("D1:D3")
    Range("A1:A3").Copy Range("D1")
    
    'Range.Copy to other worksheets
    Worksheets("Sheet1").Range("A1").Copy Worksheets("Sheet2").Range("A1")
    
    'Range.Copy to other workbooks
    Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1").Copy _
        Workbooks("Book2.xlsx").Worksheets("Sheet1").Range("A1")

End Sub


Sub Paste_Values_Examples()
'Set the cells' values equal to another to paste values

    'Set a cell's value equal to another cell's value
    Range("C1").Value = Range("A1").Value
    Range("D1:D3").Value = Range("A1:A3").Value
     
    'Set values between worksheets
    Worksheets("Sheet2").Range("A1").Value = Worksheets("Sheet1").Range("A1").Value
     
    'Set values between workbooks
    Workbooks("Book2.xlsx").Worksheets("Sheet1").Range("A1").Value = _
        Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1").Value
        
End Sub


Sub PasteSpecial_Examples()
'Use the Range.PasteSpecial method for other paste types

    'Copy and PasteSpecial a Range
    Range("A1").Copy
    Range("A3").PasteSpecial Paste:=xlPasteFormats
    
    'Copy and PasteSpecial a between worksheets
    Worksheets("Sheet1").Range("A2").Copy 
    Worksheets("Sheet2").Range("A2").PasteSpecial Paste:=xlPasteFormulas
    
    'Copy and PasteSpecial between workbooks
    Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1").Copy
    Workbooks("Book2.xlsx").Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteFormats
    
    'Disable marching ants around copied range
    Application.CutCopyMode = False

End Sub

Paste Data Below the Last Used Row

One of the most common questions I get about copying and pasting with VBA is, how do I paste to the bottom of a range that is constantly changing?  I first want to find the last row of data, then copy & paste below it.

To answer this question, I created a free training video on how to paste data below the last used row in a sheet with VBA.  Can I send you the video?  Please click the image below to get the video.

Paste Data Below Last Used Row VBA Free Training

Free Training on Macros & VBA

The 3 videos above are from my VBA Pro Course.  If you want to learn more about macros and VBA then checkout my free 3-part video training series.

I will also send you info on the VBA Pro Course, that will take you from beginner to expert.  Click the link below to get instant access.

Free Training on Macros & VBA

Please leave a comment below with any questions.  Thanks!

Содержание

  1. Range.Copy method (Excel)
  2. Syntax
  3. Parameters
  4. Return value
  5. Example
  6. Support and feedback
  7. VBA – Cut, Copy, Paste from a Macro
  8. Copy (Cut) and Paste a Single Cell
  9. VBA Coding Made Easy
  10. Copy Selection
  11. Copy (Cut) and Paste a Range of Cells
  12. Copy (Cut) and Paste an Entire Column
  13. Copy (Cut) and Paste an Entire Row
  14. Copy (Cut) and Paste to Another Worksheet or Workbook
  15. Value Paste
  16. Paste Special
  17. Clear Clipboard
  18. VBA Code Examples Add-in
  19. Excel Macro: Copy and Paste a Range
  20. Range.Copy method
  21. Syntax
  22. Example 1: Copy Range and paste to another worksheet
  23. Example 2: copy row
  24. Example 3: copy row and paste to new inserted row
  25. Example 4: copy column
  26. Example 5: copy multiple Range to a new Workbook
  27. Example 6: destination argument omitted
  28. Range.PasteSpecial method
  29. Syntax
  30. Parameters
  31. XlPasteType enumeration
  32. XlPasteSpecialOperation enumeration
  33. Example 1: paste values
  34. Example 2: paste formats
  35. Example 3: paste formulas
  36. Example 4: EntireRow copy and paste
  37. Example 5: Multiply
  38. Example 6: Add
  39. How to Use This Macro
  40. Excel VBA Copy Range to Another Sheet with Formatting
  41. VBA Reference
  42. 120+ Project Management Templates
  43. How to Copy Range to Another Sheet with Formatting in Excel VBA
  44. How to copy the Excel Range including Column widths
  45. Method 1: Using PasteSpecial Method to Copy Range and Paste in Another Sheet with Formatting and Column Widths.
  46. Method 3: Copying Entire Range of Columns and Paste in Another Sheet.
  47. Method 3: Explicitly specifying the Column Widths
  48. Copy Range Values to Another Sheet with out Formatting in Excel VBA
  49. Copy Formats of a Range to Another Sheet using Excel VBA
  50. Copy Formulas of a Range to Another Sheet using Excel VBA
  51. CopyPaste Only the Border of a Range to Another Sheet in Excel VBA
  52. Best Practices to follow while Copying Excel Range to another Sheet

Range.Copy method (Excel)

Copies the range to the specified range or to the Clipboard.

Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.

Syntax

expression.Copy (Destination)

expression A variable that represents a Range object.

Parameters

Name Required/Optional Data type Description
Destination Optional Variant Specifies the new range to which the specified range will be copied. If this argument is omitted, Microsoft Excel copies the range to the Clipboard.

Return value

Example

The following code example copies the formulas in cells A1:D4 on Sheet1 into cells E5:H8 on Sheet2.

The following code example inspects the value in column D for each row on Sheet1. If the value in column D equals A, the entire row is copied onto SheetA in the next empty row. If the value equals B, the row is copied onto SheetB.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA – Cut, Copy, Paste from a Macro

In this Article

In this tutorial, you will learn several different methods to Copy & Paste and Cut & Paste using a VBA macro. Read the companion tutorial on Value Pasting and PasteSpecial for more advanced copying and pasting options.

To use this code: Open the Visual Basic Editor (Alt + F11), Insert a new module (Insert > Module) and copy & paste the desired code into the module.

Copy (Cut) and Paste a Single Cell

This example copies or cuts and pastes a single cell, A1 over to B1:

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!

Copy Selection

If you want to copy the active selection use this:

Copy (Cut) and Paste a Range of Cells

This example copies or cuts and pastes a range of cells, A1:A3 over to B1:B3 :

Copy (Cut) and Paste an Entire Column

Below we will demonstrate a couple of quick examples. Read our article on Copying and Pasting Rows and Columns for detailed examples, explanations, and variations.

This example copies or cuts and pastes an entire column, A over to B:

Copy (Cut) and Paste an Entire Row

This example copies or cuts and pastes an entire row, 1 over to 2:

Copy (Cut) and Paste to Another Worksheet or Workbook

Value Paste

Normally, when you Copy and Paste you Paste all the properties of a cell: formatting, formulas, etc.. Value Pasting allows you to Copy and Paste cells’ values and nothing else. The easiest way to Value Paste in VBA is to define the cell’s value directly:

Paste Special

Paste Special allows you to Copy and Paste specific properties of cells (examples: formats, values, column widths, etc.). It also allows you to perform special paste operations (examples: skip blanks, transpose). We will look at several examples below, but for an in-depth read our tutorial on Value Pasting and Paste Special.

Clear Clipboard

After Copying & Pasting you might want to clear the clipboard (we do in some of the code examples above). To clear the Excel clipboard, we set Application.CutCopyMode to False:

This will clear Excel’s clipboard. However, it will not clear the Windows Clipboard. To clear the Window’s clipboard follow the instructions here.

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.

Источник

Excel Macro: Copy and Paste a Range

One of the most common action you’ll need to learn is copying and pasting a range of data. It’s very easy to do this manually. In normal data, we use either CTRL + C to copy a selection of data and then use CTRL + V to paste the selected data in the target cell. It’s just as easy to copy and paste via VBA.

Range.Copy method

Range.Copy Method is a very convenient Method to copy and paste Range to destination in one line of code. All the formatting and formulas will be copied and pasted.

Syntax

Destination is optional. If this argument is omitted, Microsoft Excel copies the range to the Clipboard. It returns Variant.

Example 1: Copy Range and paste to another worksheet

The below code copy Sheet1 A1 to Sheet2 B1.

If there are more than one Range to copy, you just need to specific the first Range of the destination.

Example 2: copy row

The below code copy from Sheet1 row 1:2 to Sheet2 row 6.

Note that if you copy a row to destination, the destination Range must be a Row or a Range in column A.

Example 3: copy row and paste to new inserted row

Example 4: copy column

The below code copy Sheet1 column A:B to Sheet2 column B:C (because it pastes at B1).

Example 5: copy multiple Range to a new Workbook

In case the copied Columns are not adjacent to each other, Set a Range to combine those Columns (or Rows).

The below code copy range1 and then paste to A1 of new workbook.

Example 6: destination argument omitted

The following code example inspects the value in column D for each row on Sheet1. If the value in column D equals A, the entire row is copied onto SheetA in the next empty row. If the value equals B, the row is copied onto SheetB.

Range.PasteSpecial method

When working with your spreadsheet, you likely often have to copy formulas and paste them as values. To do this in a macro, you can use the PasteSpecial method.

Syntax

It returns Variant.

Parameters

Name Required/Optional Data type Description
Paste Optional XlPasteType Specifies the part of the range to be pasted.
Operation Optional XlPasteSpecialOperation Specifies how numeric data will be calculated with the destinations cells on the worksheet.
SkipBlanks Optional Variant True to have blank cells in the range on the clipboard not be pasted into the destination range. The default value is False.
Transpose Optional Variant True to transpose rows and columns when the range is pasted. The default value is False.

XlPasteType enumeration

Name Value Description
xlPasteAll -4104 Everything will be pasted.
xlPasteAllExceptBorders 7 Everything except borders will be pasted.
xlPasteAllMergingConditionalFormats 14 Everything will be pasted and conditional formats will be merged.
xlPasteAllUsingSourceTheme 13 Everything will be pasted using the source theme.
xlPasteColumnWidths 8 Copied column width is pasted.
xlPasteComments -4144 Comments are pasted.
xlPasteFormats -4122 Copied source format is pasted.
xlPasteFormulas -4123 Formulas are pasted.
xlPasteFormulasAndNumberFormats 11 Formulas and Number formats are pasted.
xlPasteValidation 6 Validations are pasted.
xlPasteValues -4163 Values are pasted.
xlPasteValuesAndNumberFormats 12 Values and Number formats are pasted.

XlPasteSpecialOperation enumeration

Name Value Description
xlPasteSpecialOperationAdd 2 Copied data will be added to the value in the destination cell.
xlPasteSpecialOperationDivide 5 Copied data will divide the value in the destination cell.
xlPasteSpecialOperationMultiply 4 Copied data will multiply the value in the destination cell.
xlPasteSpecialOperationNone -4142 No calculation will be done in the paste operation.
xlPasteSpecialOperationSubtract 3 Copied data will be subtracted from the value in the destination cell.

Example 1: paste values

Note: To remove the animation around the copied cell add below code:

Example 2: paste formats

Example 3: paste formulas

Example 4: EntireRow copy and paste

Example 5: Multiply

This example replaces the data in cells A1:C2 on Sheet1 with the multiply of the existing contents and cells D1 on Sheet1.

1
2
A B C D
1 2 3 3
4 5 6

VBA Code

Result

1
2
A B C D
3 6 9 3
12 15 18

Example 6: Add

This example replaces the data in cells D1:D2 on Sheet1 with the sum of the existing contents and cells A1:A2 on Sheet1.

1
2
A B C D
1 2 3 3
4 5 6 3

VBA Code

Result

1
2
A B C D
1 2 3 4
4 5 6 7

How to Use This Macro

Most VBA code should be placed in Standard Modules unless specified.

If you see a comment ‘—————— Modules—————— in the code header that means put the code in a Standard Module. For more information, learn this course: Where should I put the Excel VBA code?

The following steps teach you how to put VBA code into a Standard Module:

  1. Activate the Visual Basic Editor by pressing ALT + F11 .
  2. Right-click the project/workbook name in the Project Window.
  3. Choose Insert ->Module.
  4. Type or paste the code in the newly created module. You will probably need to change the sheet name, the range address, and the save location.
  5. Click Run button on the Visual Basic Editor toolbar.
  6. For more information, learn this course: Programming with Excel VBA

Источник

Excel VBA Copy Range to Another Sheet with Formatting

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:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word 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
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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

Источник

Понравилась статья? Поделить с друзьями:
  • Copy paste word table
  • Copy paste to word not working
  • Copy paste rows excel
  • Copy paste all cells vba excel
  • Copy paint to word