Excel vba paste formats

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

Специальная вставка (метод PasteSpecial объекта Range) применяется в VBA Excel для вставки ячеек из буфера обмена с учетом заданных параметров.

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

Синтаксис

Range.PasteSpecial (Paste, Operation, SkipBlanks, Transpose)

Специальная вставка работает только с данными ячеек, скопированными в буфер обмена методом Range.Copy. При попытке применить метод Range.PasteSpecial к ячейкам, вырезанным в буфер обмена методом Range.Cut, возникает ошибка.

Параметры специальной вставки

Список параметров метода Range.PasteSpecial:

Параметры Описание
Paste Необязательный параметр. Константа из коллекции XlPasteType, указывающая на часть данных вставляемого диапазона, которую следует вставить. По умолчанию вставляются все данные.
Operation Необязательный параметр. Константа из коллекции XlPasteSpecialOperation, указывающая на математические операции, которые следует провести со скопированными данными и данными в ячейках назначения. По умолчанию вычисления не производятся.
SkipBlanks Необязательный параметр. Булево значение, которое указывает, вставлять ли в конечный диапазон пустые ячейки: True – не вставлять, False – вставлять (значение по умолчанию).
Transpose Необязательный параметр. Булево значение, которое указывает, следует ли транспонировать строки и столбцы при вставке диапазона: True – транспонировать, False – не транспонировать (значение по умолчанию).

Смотрите другой способ транспонировать диапазоны ячеек и двумерные массивы.

Константы XlPasteType

Список констант из коллекции XlPasteType, которые могут быть использованы в качестве аргумента параметра Paste:

Константа Значение Описание
xlPasteAll -4104 Вставка всех данных (по умолчанию).
xlPasteAllExceptBorders 7 Вставка всех данных, кроме границ.
xlPasteAllMergingConditionalFormats 14 Вставка всех данных со слиянием условных форматов исходного и нового диапазонов.
xlPasteAllUsingSourceTheme 13 Вставка всех данных с использованием исходной темы.
xlPasteColumnWidths 8 Вставка ширины столбцов.
xlPasteComments -4144 Вставка комментариев.
xlPasteFormats -4122 Вставка форматов исходного диапазона.
xlPasteFormulas -4123 Вставка формул.
xlPasteFormulasAndNumberFormats 11 Вставка формул и форматов чисел.
xlPasteValidation 6 Вставка правил проверки данных из ячеек исходного диапазона в новый диапазон.
xlPasteValues -4163 Вставка значений.
xlPasteValuesAndNumberFormats 12 Вставка значений и форматов чисел.

Константы XlPasteSpecialOperation

Список констант из коллекции XlPasteSpecialOperation, которые могут быть использованы в качестве аргумента параметра Operation:

Константа Значение Описание
xlPasteSpecialOperationAdd 2 Скопированные данные будут добавлены к значениям в ячейках назначения.
xlPasteSpecialOperationDivide 5 Скопированные данные разделят значения в ячейках назначения.
xlPasteSpecialOperationMultiply 4 Скопированные данные будут перемножены со значениями в ячейках назначения.
xlPasteSpecialOperationNone -4142 Вычисления не выполняются при вставке данных (по умолчанию).
xlPasteSpecialOperationSubtract 3 Скопированные данные будут вычтены из значений в ячейках назначения.

Примеры

Примеры копирования и специальной вставки актуальны для диапазона "A1:B8" активного листа, ячейки которого заполнены числами:

‘Копирование диапазона ячеек в буфер обмена:

Range(«A1:B8»).Copy

‘Специальная вставка только значений:

Range(«D1»).PasteSpecial Paste:=xlPasteValues

‘Специальная вставка с делением значений ячеек конечного

‘диапазона на значения ячеек диапазона из буфера обмена:

Range(«D1»).PasteSpecial Operation:=xlPasteSpecialOperationDivide

‘Специальная вставка только значений с транспонированием строк и столбцов:

Range(«G1»).PasteSpecial Paste:=xlPasteValues, Transpose:=True


Like a worksheet, we have a Paste Special method to copy data and paste it on a different cell range. It allows us to paste the data as itself or only the formulas or only the values and the same fashion. We can use Paste Special in VBA using the range property method: paste special() providing the type we want in the brackets.

Paste Special in excelPaste special in Excel allows you to paste partial aspects of the data copied. There are several ways to paste special in Excel, including right-clicking on the target cell and selecting paste special, or using a shortcut such as CTRL+ALT+V or ALT+E+S.read more serves in many ways in our daily work. Using Paste Special, we can do many more things than usual. Of course, copy and paste are everywhere in the computer world. But, Paste Special is the advanced thing in Excel.

Like regular Excel Paste Special in VBA, too, we have a Paste Special method to paste the copied data. Copying things in Excel is not strange for Excel users. They copy and paste, and most of the time, they use Paste Special to serve their purpose in many ways.

VBA Paste Special

In regular Excel, paste includes many options like paste only values, paste formulas, paste formats, etc.

Paste Special

Paste Special has to paste, operate, skip blanks, and transpose like in VBA. So, we have all the parameters with the Paste Special method.

Table of contents
  • Paste Special in VBA
    • The Formula of Paste Special in VBA
    • Examples of Paste Special in Excel VBA
      • Example #1 – Paste only Values using VBA PasteSpecial Function
      • Example #2 – Paste All using VBA PasteSpecial
      • Example #3 – Paste Formats using VBA PasteSpecial Function
      • Example #4 – Paste Column Width using VBA Paste Special
      • Example #5 – Copy the Data from One Sheet to Another Sheet using VBA Paste Special Option
    • Things to Remember About Excel VBA PasteSpecial Function
    • Recommended Articles

The Formula of Paste Special in VBA

Below is the formula for Paste Special in VBA.

VBA PasteSpecial

The Paste Special is available with the VBA Range objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more because after copying the data, we will be pasting it in the cell range, so the Paste Special method is available with the Range object.

Paste Type: After copying the data, how do you want to paste it? Whether you want to paste values, formulas, formats, validation, etc. Below is the complete list of options available under Paste Type.

Option of paste type

Paste Special Operation: While pasting, do you want to perform any operations like add, subtract, division, multiplication, or none?

Paste special operation

  • [Skip Blanks]: If you want to skip blanks, you can choose TRUE or FALSE.
  • [Transpose]: If you want to transpose the data, you can choose TRUE or FALSE.

Examples of Paste Special in Excel VBA

The following are examples of Paste Special in VBA.

You can download this VBA Paste Special Template here – VBA Paste Special Template

Example #1 – Paste only Values using VBA PasteSpecial Function

In the first example, we will perform pasting only values using paste special. For example, assume below is the data you have in the sheet name called “Sales Data.”

VBA PasteSpecial Example 1

Now, we will perform the task of copying and pasting using several Paste Special methods. Follow the below steps.

Step 1: Create a Macro name first.

VBA Paste Special Example 1

Step 2: First, copy the range A1 to D14 from the sheet name “Sales Data.” To copy the range, apply the below code.

Code: 

Range("A1:D14").Copy

VBA PasteSpecial Example 1-1

Step 3: After copying the data, we will paste the values from G1 to J14. First, reference the range.

Code:

Range ("G1:J14")

VBA PasteSpecial Example 1-2

Step 4: After selecting the range, we need to paste. So, put a dot (.) and select the Paste Special method.

Code:

Sub PasteSpecial_Example1()

    Range("A1:D14").Copy
    Range("G1:J14").PasteSpecial

End Sub

VBA PasteSpecial Example 1-3

Step 5: From the dropdown list, select the option “xlPasteValues.”

Code:

Sub PasteSpecial_Example1()

   Range("A1:D14").Copy
   Range("G1:J14").PasteSpecial xlPasteValues

End Sub

VBA PasteSpecial Example 1-4

Step 6: Run this code using the F5 key or manually and see what happens.

VBA PasteSpecial Example 1-5

So, our code copied the data from A1 to D14 and pasted it from G1 to J14 as values.

It has performed the task of shortcut excel keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more in worksheet ALT + E + S + V.

Shortcut key to paste

Example #2 – Paste All using VBA PasteSpecial

Now, we will see what happens if we perform the task of xlPasteAll.

Code:

Sub PasteSpecial_Example2()

   Range("A1:D14").Copy
   Range("G1:J14").PasteSpecial xlPasteAll

End Sub

Now, if you run this code manually through the “Run” option, by pressing the F5 key, we will have as it is data.

VBA PasteSpecial Example 1-8

Example #3 – Paste Formats using VBA PasteSpecial Function

Now, we will see how to paste only formats. The below code would do the job for us.

Code:

Sub PasteSpecial_Example3()

   Range("A1:D14").Copy
   Range("G1:J14").PasteSpecial xlPasteFormats

End Sub

VBA PasteSpecial Example 1-10

If you run this code using the F5 key or manually, we will get the only format of the copied range, nothing else.

VBA PasteSpecial Example 1-11

Example #4 – Paste Column Width using VBA Paste Special

Now, we will see how to paste only column widthA user can set the width of a column in an excel worksheet between 0 and 255, where one character width equals one unit. The column width for a new excel sheet is 8.43 characters, which is equal to 64 pixels.read more from the copied range. For this, we have increased the width of one of my data columns.

VBA PasteSpecial Example 1-13

Apply the below code. It will paste only the column width of the copied range.

Code:

Sub PasteSpecial_Example3()

 Range("A1:D14").Copy
 Range("G1:J14").PasteSpecial xlPasteColumnWidths

End Sub

VBA PasteSpecial Example 1-14

Run this code and see the difference in the column width.

VBA PasteSpecial Example 1-15

Now, the “Sales” column width increases to the width of our copied range column.

Example #5 – Copy the Data from One Sheet to Another Sheet using VBA Paste Special Option

We have seen how to copy and paste the data on the same sheet. Now, we will learn how to paste from one sheet to another sheet.

Step 1: Before we select the range, we need to tell from which sheet we need to select the data.

Code:

Sub PasteSpecial_Example5()

   Worksheets ("Sales Data")

End Sub

Example 2

Step 2: After selecting the sheet by its name, we need to select the range in that sheet. They copy it.

Code:

Sub PasteSpecial_Example5()

  Worksheets("Sales Data").Range("A1:D14").Copy

End Sub

Example 2-1

The above code says in the sheet name “Sales Data” copy the Range (“A1:D14”).

Step 3: Since we are pasting it on a different sheet, we must select the sheet by its name.

Code:

Sub PasteSpecial_Example5()

  Worksheets("Sales Data").Range("A1:D14").Copy
  Worksheets ("Month Sheet")

End Sub

Example 2-2

Step 4: Now, in the sheet “Month Sheet,” select the range.

Code:

Sub PasteSpecial_Example5()

  Worksheets("Sales Data").Range("A1:D14").Copy
  Worksheets("Month Sheet").Range ("A1:D14")

End Sub

Example 2-3

Step 5: Using Paste Special, we will be pasting values and format.

Code:

Sub PasteSpecial_Example5()

  Worksheets("Sales Data").Range("A1:D14").Copy
  Worksheets("Month Sheet").Range("A1:D14").PasteSpecial xlPasteValuesAndNumberFormats

End Sub

Example 2-4

Step 6: We are not only pasting values and format using VBA Paste Special, but we are pasting it as TRANSPOSE as well.

Code:

Sub PasteSpecial_Example5()

Worksheets("Sales Data").Range("A1:D14").Copy
Worksheets("Month Sheet").Range("A1:D14").PasteSpecial xlPasteValuesAndNumberFormats, Transpose:=True

End Sub

Example 2-5

Now run this code. It will copy and transpose the data to the “Month Sheet.”

Example 2-6

Things to Remember About Excel VBA PasteSpecial Function

  • To skip blanks, we must enter the argument as TRUE by default. It takes FALSE.
  • If we want to transpose the data, we must select the transpose as TRUE.
  • We can perform only one Paste Special at a time.

Recommended Articles

This article has been a guide to Excel VBA PasteSpecial. Here, we learn the top 5 ways to use VBA PasteSpecial function, practical examples, and downloadable VBA codes. Below are some useful Excel articles related to VBA: –

  • Record VBA MacrosVBA Macros are the lines of code that instruct the excel to do specific tasks, i.e., once the code is written in Visual Basic Editor (VBE), the user can quickly execute the same task at any time in the workbook. It thus eliminates the repetitive, monotonous tasks and automates the process.read more
  • VBA PasteThere are three different ways to paste some data from place to another in a worksheet using VBA, the first method is to normally refer the values from one cell to another cell using the assignment operator, another method is by using the paste function and third method is by using the pastespecial function.read more
  • VBA Code in Excel FunctionVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more
  • How to Transpose in VBA?Transpose function flips rows and columns in a data table, turning rows into columns and columns into rows.read more
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

Содержание

  1. Worksheet.Paste method (Excel)
  2. Syntax
  3. Parameters
  4. Remarks
  5. Example
  6. Support and feedback
  7. Метод Worksheet.Paste (Excel)
  8. Синтаксис
  9. Параметры
  10. Замечания
  11. Пример
  12. Поддержка и обратная связь
  13. Метод Range.PasteSpecial (Excel)
  14. Синтаксис
  15. Параметры
  16. Возвращаемое значение
  17. Пример
  18. Поддержка и обратная связь
  19. VBA Value Paste & PasteSpecial
  20. Paste Values
  21. Copy and Value Paste to Different Sheet
  22. Copy and Value Paste Ranges
  23. Copy and Value Paste Columns
  24. Copy and Value Paste Rows
  25. Paste Values and Number Formats
  26. VBA Coding Made Easy
  27. .Value instead of .Paste
  28. Cell Value vs. Value2 Property
  29. Copy Paste Builder
  30. Paste Special – Formats and Formulas
  31. Paste Formats
  32. Paste Formulas
  33. Paste Formulas and Number Formats
  34. Paste Special – Transpose and Skip Blanks
  35. Paste Special – Transpose
  36. Paste Special – Skip Blanks
  37. Other Paste Special Options
  38. Paste Special – Comments
  39. Paste Special – Validation
  40. Paste Special – All Using Source Theme
  41. Paste Special – All Except Borders
  42. PasteSpecial – Column Widths
  43. PasteSpecial – All MergingConditionalFormats
  44. VBA Code Examples Add-in

Worksheet.Paste method (Excel)

Pastes the contents of the Clipboard onto the sheet.

Syntax

expression.Paste (Destination, Link)

expression A variable that represents a Worksheet object.

Parameters

Name Required/Optional Data type Description
Destination Optional Variant A Range object that specifies where the Clipboard contents should be pasted. If this argument is omitted, the current selection is used. This argument can be specified only if the contents of the Clipboard can be pasted into a range. If this argument is specified, the Link argument cannot be used.
Link Optional Variant True to establish a link to the source of the pasted data. If this argument is specified, the Destination argument cannot be used. The default value is False.

If you don’t specify the Destination argument, you must select the destination range before you use this method.

This method may modify the sheet selection, depending on the contents of the Clipboard.

Example

This example copies data from cells C1:C5 on Sheet1 to cells D1:D5 on Sheet1.

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.

Источник

Метод Worksheet.Paste (Excel)

Вставляет содержимое буфера обмена на лист.

Синтаксис

expression. Вставка (назначение, ссылка)

Выражение Переменная, представляющая объект Worksheet .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Destination Необязательный Variant Объект Range , указывающий место вставки содержимого буфера обмена. Если этот аргумент опущен, используется текущий выбор. Этот аргумент можно указать только в том случае, если содержимое буфера обмена можно вставить в диапазон. Если этот аргумент указан, аргумент Link использовать нельзя.
Link Необязательный Variant Значение true , чтобы установить связь с источником вставленных данных. Если этот аргумент указан, аргумент Destination использовать нельзя. Значение по умолчанию — False.

Замечания

Если аргумент Destination не указан, перед использованием этого метода необходимо выбрать диапазон назначения.

Этот метод может изменить выбранный лист в зависимости от содержимого буфера обмена.

Пример

В этом примере данные копируются из ячеек C1:C5 на Листе1 в ячейки D1:D5 на Листе1.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Метод Range.PasteSpecial (Excel)

Вставляет объект Range , скопированный в указанный диапазон.

Синтаксис

expression. PasteSpecial (Paste, Operation, SkipBlanks, Transpose)

выражение: переменная, представляющая объект Range.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Paste Необязательный XlPasteType Часть вставляемого диапазона, например xlPasteAll или xlPasteValues.
Операция Необязательный XlPasteSpecialOperation Операция вставки, например xlPasteSpecialOperationAdd.
SkipBlanks Необязательный Variant Значение true , чтобы пустые ячейки в диапазоне в буфере обмена не вставились в целевой диапазон. Значение по умолчанию — False.
Transpose Необязательный Variant Значение true для транспонирования строк и столбцов при вставке диапазона. Значение по умолчанию — False.

Возвращаемое значение

Пример

В этом примере данные в ячейках D1:D5 на Листе1 заменяются суммой существующего содержимого и ячеек C1:C5 на Листе1.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

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.

Источник

Like this post? Please share to your friends:
  • Excel vba for pivot table
  • Excel vba paste destination
  • Excel vba for overflow
  • Excel vba overflow run time error 6
  • Excel vba for next error