Специальная вставка (метод 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 |
This Excel VBA tutorial explains how to use Range.PasteSpecial Method to paste special such as paste values.
In Excel worksheet, if you copy a Cell and then Paste Special, you can see a list of options. The most commonly used Paste Special is Paste Values, in order to remove all the formula.
In Excel VBA, Paste Speical is done through Range.PasteSpecial Method.
Syntax of Range.PasteSpecial Method
Range.PasteSpecial(Paste, Operation, SkipBlanks, Transpose)
Name | Required/Optional | Description | ||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Paste | Optional |
|
||||||||||||||||||||||||||
Operation | Optional |
|
||||||||||||||||||||||||||
SkipBlanks | Optional | 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 | True to transpose rows and columns when the range is pasted.The default value is False. |
Example 1 – Paste Value
The below VBA copy the whole active worksheet and paste as value.
Public Sub pasteVal() ActiveSheet.Cells.Copy ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues End Sub
Example 2 – Multiply
Suppose we want to multiply Range A1:C2 by 2.
Public Sub pasteMultiply()
Range("E1").Copy 'Suppose E1 contains value 2
Range("A1:C2").PasteSpecial Operation:=xlPasteSpecialOperationMultiply
End Sub
Result
Copy and Paste in one line
Incidentally, if you just want to copy and paste normally, you can use Copy Method with Destination argument.
The below example copy Range A1:C2 and paste in A10.
Public Sub cpy() Range("A1:C2").Copy Destination:=Range("A10") End Sub
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Range.PasteSpecial method (Excel) |
vbaxl10.chm144238 |
vbaxl10.chm144238 |
excel |
Excel.Range.PasteSpecial |
d3e991f2-7ef7-2ebc-d4bc-ba4c26be472e |
05/11/2019 |
medium |
Range.PasteSpecial method (Excel)
Pastes a Range object that has been copied into the specified range.
Syntax
expression.PasteSpecial (Paste, Operation, SkipBlanks, Transpose)
expression A variable that represents a Range object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Paste | Optional | XlPasteType | The part of the range to be pasted, such as xlPasteAll or xlPasteValues. |
Operation | Optional | XlPasteSpecialOperation | The paste operation, such as xlPasteSpecialOperationAdd. |
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. |
Return value
Variant
Example
This example replaces the data in cells D1:D5 on Sheet1 with the sum of the existing contents and cells C1:C5 on Sheet1.
With Worksheets("Sheet1") .Range("C1:C5").Copy .Range("D1:D5").PasteSpecial _ Operation:=xlPasteSpecialOperationAdd End With
[!includeSupport and feedback]
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:
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:
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:
Sheets("Sheet1").Columns("D").Copy
Sheets("Sheet2").Columns("B").PasteSpecial Paste:=xlPasteValues
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
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!
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.
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
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
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
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
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
Other Paste Special Options
Sheets("Sheet1").Range("A1").Copy Sheets("Sheet1").Range("E1").PasteSpecial xlPasteComments
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Paste Special – Validation
Sheets("Sheet1").Range("A1:A4").Copy
Sheets("Sheet1").Range("B1:B4").PasteSpecial xlPasteValidation
Paste Special – All Using Source Theme
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
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
PasteSpecial – All MergingConditionalFormats
Range("A1:A4").Copy
Range("C1").PasteSpecial
Range("E1").PasteSpecial xlPasteAllMergingConditionalFormats
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.
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Paste Special (wallstreetmojo.com)
In regular Excel, paste includes many options like paste only values, paste formulas, paste formats, etc.
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.
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.
Paste Special Operation: While pasting, do you want to perform any operations like add, subtract, division, multiplication, or none?
- [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.”
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.
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
Step 3: After copying the data, we will paste the values from G1 to J14. First, reference the range.
Code:
Range ("G1:J14")
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
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
Step 6: Run this code using the F5 key or manually and see what happens.
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.
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.
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
If you run this code using the F5 key or manually, we will get the only format of the copied range, nothing else.
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.
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
Run this code and see the difference in the column width.
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
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
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
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
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
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
Now run this code. It will copy and transpose the data to the “Month Sheet.”
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