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
Специальная вставка (метод 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 |
Содержание
- Метод Range.PasteSpecial (Excel)
- Синтаксис
- Параметры
- Возвращаемое значение
- Пример
- Поддержка и обратная связь
- Range.PasteSpecial method (Excel)
- Syntax
- Parameters
- Return value
- Example
- Support and feedback
- Метод Worksheet.PasteSpecial (Excel)
- Синтаксис
- Параметры
- Замечания
- Пример
- Поддержка и обратная связь
- Worksheet.PasteSpecial method (Excel)
- Syntax
- Parameters
- Remarks
- Example
- Support and feedback
- VBA PasteSpecial Values, Formats, Formulas and more
- The VBA Tutorials Blog
- Our Dataset
- The Range Object
- PasteSpecial Pasting Options
- Paste as XlPasteType
- Value and Formats Example
- Pasting Formulas with VBA PasteSpecial
- Formatting and Validation
- Operation as XlPasteSpecialOperation
- Commutative Operations
- Non-commutative Operations
- Performing math on entire range based on value in one cell
- PasteSpecial Behavior Options
- The SkipBlanks Option
- The Transpose Option
- Conclusion
Метод 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 и обратная связь.
Источник
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
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.
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.PasteSpecial (Excel)
Вставляет содержимое буфера обмена на лист в указанном формате. Используйте этот метод для вставки данных из других приложений или для вставки данных в определенном формате.
Синтаксис
expression. PasteSpecial (Format, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, NoHTMLFormatting)
Выражение Переменная, представляющая объект Worksheet .
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
Format | Необязательный | Variant | Строка, указывающая формат буфера обмена данных. |
Link | Необязательный | Variant | Значение true , чтобы установить связь с источником вставленных данных. Если исходные данные не подходят для связывания или исходное приложение не поддерживает связывание, этот параметр игнорируется. Значение по умолчанию — False. |
DisplayAsIcon | Необязательный | Variant | Значение true для отображения вставленных данных в виде значка. Значение по умолчанию — False. |
IconFileName | Необязательный | Variant | Имя файла, содержащего значок для использования, если DisplayAsIcon имеет значение True. |
IconIndex | Необязательный | Variant | Номер индекса значка в файле значка. |
IconLabel | Необязательный | Variant | Текстовая метка значка. |
NoHTMLFormatting | Необязательный | Variant | Значение true , чтобы удалить все форматирование, гиперссылки и изображения из HTML. Значение False для вставки HTML как есть. Значение по умолчанию — False. |
Замечания
Значение NoHTMLFormatting имеет значение только в том случае, если Format = «HTML»; Во всех остальных случаях параметр NoHTMLFormatting игнорируется.
Перед использованием этого метода необходимо выбрать диапазон назначения.
Этот метод может изменить выбранный лист в зависимости от содержимого буфера обмена.
Для разработчиков языков, отличных от английского, можно заменить одну из следующих констант (0–5), чтобы она соответствовала строковой эквивалентной формату файла рисунка.
Аргумент Format | Эквивалент строки |
---|---|
0 | «Рисунок (PNG)» |
1 | «Рисунок (JPEG)» |
2 | «Рисунок (GIF)» |
3 | «Изображение (расширенный метафайл)» |
4 | «Растровое изображение» |
5 | «Объект документа Microsoft Office» |
Пример
В этом примере объект документа Microsoft Word вставляется из буфера обмена в ячейку D1 на Листе1.
В этом примере объект рисунка вставляется и не отображается в виде значка.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Worksheet.PasteSpecial method (Excel)
Pastes the contents of the Clipboard onto the sheet, using a specified format. Use this method to paste data from other applications or to paste data in a specific format.
Syntax
expression.PasteSpecial (Format, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, NoHTMLFormatting)
expression A variable that represents a Worksheet object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Format | Optional | Variant | A string that specifies the Clipboard format of the data. |
Link | Optional | Variant | True to establish a link to the source of the pasted data. If the source data isn’t suitable for linking or the source application doesn’t support linking, this parameter is ignored. The default value is False. |
DisplayAsIcon | Optional | Variant | True to display the pasted data as an icon. The default value is False. |
IconFileName | Optional | Variant | The name of the file that contains the icon to use if DisplayAsIcon is True. |
IconIndex | Optional | Variant | The index number of the icon within the icon file. |
IconLabel | Optional | Variant | The text label of the icon. |
NoHTMLFormatting | Optional | Variant | True to remove all formatting, hyperlinks, and images from HTML. False to paste HTML as is. The default value is False. |
NoHTMLFormatting only matters when Format = «HTML»; in all other cases, NoHTMLFormatting is ignored.
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.
For developers of languages other than English, you can substitute one of the following constants (0-5) to correspond with the string equivalent of the picture file format.
Format argument | String equivalent |
---|---|
0 | «Picture (PNG)» |
1 | «Picture (JPEG)» |
2 | «Picture (GIF)» |
3 | «Picture (Enhanced Metafile)» |
4 | «Bitmap» |
5 | «Microsoft Office Drawing Object» |
Example
This example pastes a Microsoft Word document object from the Clipboard to cell D1 on Sheet1.
This example pastes a picture object and does not display it as an icon.
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 PasteSpecial Values, Formats, Formulas and more
The VBA Tutorials Blog
The copy/paste function of computers is so commonplace it is almost second nature to most people now. We trust computers to copy entire texts perfectly when we press Ctrl+C / Ctrl+V, and there’s no reason not to trust them. If we humans had to type out a 50-digit code, we would almost certainly make a mistake — at the very least, it would take much longer than the copy/paste we are used to.
However, sometimes we want to copy more than just plain text. Excel offers all kinds of features, like conditional formatting, data validation, data-type formatting, and beautifying aspects like borders and cell colors, and we can copy all of them or a subset thereof. Maybe you like your coworker’s color scheme but need static data (i.e., no formulas) or maybe the formulas are awesome and you hate the color scheme. Whatever your needs, the VBA PasteSpecial method can probably help you.
This isn’t the first time we’ve used the VBA PasteSpecial command here. A couple months ago, we had a wonderful wellsrPRO community submission showing how to paste values using VBA.
Our Dataset
In this tutorial, we are going to use a contrived dataset that incorporates many options under the PasteSpecial method so we can experiment with a number of things using the same dataset.
Our data looks like this:
Dataset with various layers of formatting, not just text and number data
Notice the different background colors and the borders in cells E1 and F1 as well as the bold font across the top row.
There are several important hidden things to note here, as well:
- Conditional formatting on the Change % column (any negative difference is green, and a positive difference over 5% is red)
- Data-type formatting for percentages or currency amounts
- Formulas in the change columns
- Data validation requiring a number greater than or equal to zero in the Quantity column
So let’s see how PasteSpecial can copy all or part of this dataset with complex formatting.
The Range Object
Before we begin our journey, we need to clarify the object associated with PasteSpecial : the Range object.
Our range in the dataset is A1:F5 . Let’s put this into a defined variable, range_to_copy , and add another range, the upper left corner of the range we want to paste into, range_for_pasting .
Now we can easily copy by referencing range_to_copy.Copy , and we can paste into A7 with range_for_pasting.PasteSpecial .
Since you’ll need to clear everything each time to play around with pasting, you can use this subroutine to clear the pasted area before pasting anything new:
This will remove data-type formatting, colors, borders, data validation, and conditional formatting in our paste range.
PasteSpecial Pasting Options
Now that we have set our ranges, we can use VBA PasteSpecial to copy different components of our range.
Although we’re focusing on copying information from Excel ranges, you can use PasteSpecial to paste almost anything copied to your clipboard.
The VBA PasteSpecial Method accepts 4 arguments, all of which are actually optional:
The first two arguments control what you want PasteSpecial to do with your copied content, and the second two arguments control the behavior of the PasteSpecial method. We’re going to cover each of these arguments in detail and give you helpful examples to demonstrate how they work.
Paste as XlPasteType
The first argument for .PasteSpecial is Paste, which determines exactly what you want to paste: formats, formulas, validation, and so on. There’s a long list of accepted values for the Paste (XlPasteType) argument. We’ll demonstrate the important ones, but here’s a complete list of all of them:
- xlPasteAll
- xlPasteAllExceptBorders
- xlPasteAllMergingConditionalFormats
- xlPasteAllUsingSourceTheme
- xlPasteColumnWidths
- xlPasteComments
- xlPasteFormats
- xlPasteFormulas
- xlPasteFormulasAndNumberFormats
- xlPasteValidation
- xlPasteValues
- xlPasteValuesAndNumberFormats
Make powerful macros with our free VBA Developer Kit
It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.
Let’s start looking at a few examples.
Value and Formats Example
Let’s pretend you just want to paste values and formats (currency, percentage, and so forth). Maybe you don’t want all the conditional formatting, coloring, and data validation. Maybe you also need the data to remain static, so you want to remove the formulas.
People need to do this all the time when storing data in a spreadsheet like a database (which is a bad idea and you should really use Access for database functions, but neverthless massive database-like spreadsheets are extremely common).
You can send your data to our range_for_pasting with this snippet:
You will end up with this as a result:
The original and value/format datasets
It’s very important that you remember to copy something to your clipboard before you try to paste. If you’re copying a range from Excel, you would just use the .Copy method of the Range object, like we did in our example.
As you can see, the cell F9 has no formula in it while the original, F3, does. Furthermore, we manually typed “three” into cell B8 (after running the macro). The data validation in our original data set would have prevented us from having a text entry, but since we only copied values and formulas, the data validation rules in our pasted range are gone. The ability to paste what you want and ignore what you don’t want makes VBA PasteSpecial a really valuable feature.
Note, if you’d rather paste the values only, without the number formats, you would run a macro with a snippet like this:
Pasting Formulas with VBA PasteSpecial
On the other hand, maybe you want just the formulas. This might be useful if you already have some complex formulas written out and need them applied to another dataset.
The original and copied dataset with only formulas copied
Here we can see the data-type formating is lost. What we’re left with are pure numbers in the change columns (no formatting for percentage or currency). You can also see the new formulas are applied to the new range, not the original. Now we can make changes in our new dataset and see the results without impacting our original dataset.
Formatting and Validation
Sometimes you don’t want the original data at all, but the rules and formats associated with the original range. The xlPasteValidation, xlPasteFormats, xlPasteColumnWidths, and xlPasteComments options allow this.
For example, say you have some complex formatting scheme, like this:
The top dataset has various formatting rules while the bottom is all formatted as «General» type
If we run this code
We end up with the bottom dataset formatted just like the top, transferring our complex formatting rules seamlessly.
The formats from the top range are transferred to the bottom
This same type of PasteSpecial can be done for validation rules, column widths, and comments. Simply change the keyword after the PasteSpecial command to xlPasteValidation, xlPasteColumnWidths, or xlPasteComments.
Another need option I find myself using a lot is the xlPasteAllExceptBorders. It’s nice to be able to paste everything but the borders into a new range.
Operation as XlPasteSpecialOperation
The second optional argument for the PasteSpecial method is Operation. This nifty little argument lets you perform mathematical operations between copied and destination data. You can use one of the four basic arthimetic operations (add, subtract, multiply, divide). These arithmetic operations are represented by the following keywords:
- xlPasteSpecialOperationAdd
- xlPasteSpecialOperationSubtract
- xlPasteSpecialOperationMultiply
- xlPasteSpecialOperationDivide
There’s also an xlPasteSpecialOperationNone keyword, but it doesn’t do any arithmetic operations. This is the default value.
When you specify an XlPasteSpecialOperation value, your VBA macro will take the range you copied, range_to_copy , and perform the mathematical operations on top of the values already existing in the range your pasting into, range_for_pasting . We’ll show a couple examples so this will make more sense.
Commutative Operations
A commutative operation is one in which a.b = b.a, where . is the operator, or in other words, when order doesn’t matter. Addition and multiplication are commutative, because the order doesn’t matter.
Let’s use these two datasets
Two sets of numbers for doing math operations
If you just want to add the numbers together, you can use this code:
Your final result will look like this:
The lower set is the addition of the original two sets
The bottom range of our dataset now contains the sum of our original bottom dataset PLUS our top dataset.
The same idea works for multiplication, except we use xlPasteSpecialOperationMultiply . Since the order doesn’t matter, you can simply replace “Add” with “Multiply” in the code above.
Non-commutative Operations
Division and subtraction are non-commutative, so order is important.
There are two possiblities for non-commutative operations for VBA PasteSpecial:
- for subtraction, the original, copied range will be subtracted from the destination range — xlPasteSpecialOperationSubtract
- for division, the destination range will be divided by the numbers in the original, copied range — xlPasteSpecialOperationDivide
With our original numbers from above, if you use the top set as range_to_copy and the bottom set as range_for_pasting , you should get whole numbers as below when using the division operator. You won’t always get whole numbers, but we made our numbers nice for you.
Let’s take a look at a division PasteSpecial example.
The bottom set is all even numbers, since we divided the original bottom set by the top set
Performing math on entire range based on value in one cell
Let’s go back to our original dataset. A nifty trick is to use a single cell, which is to say one number, to divide an entire range:
you would end up with this result:
The two datasets after dividing by D1 , which is equal to 2
You can use the same concept to add, multiple and subtract an entire range based on the contents of a single cell.
PasteSpecial Behavior Options
The other two options, both accepting Boolean values of TRUE or FALSE, are for omitting blanks in the copied range and transposing your data. This is why I said the last two arguments control the behavior of PasteSpecial, rather than controlling what’s actually pasted.
For this part, let’s use the following dataset:
Some email addresses and files to send, with a dummy dataset
The SkipBlanks Option
Using TRUE or FALSE for the SkipBlanks argument controls what the PasteSpecial method does when it encounters an empty cell. The following macro demonstrates each method and gives us the following results after running this code block:
If we skip blanks, the original data is retained, but if we do not skip blanks, the original data is overwritten with empty cells.
The Transpose Option
The final option in PasteSpecial is Transpose , which will transpose your row/column data into a column/row arrangement. This simply means your rows become columns in the new dataset and your columns become rows. We’ve got an entire post dedicated to transposing data in VBA, which includes some really neat macros for transposing data while maintaining the original cell formatting.
Using the same email and files dataset, if we set Transpose to TRUE, we get the following output:
Data before and after transposing and pasting
You can run this block to achieve the above result:
Conclusion
Each of these options can be combined with other options to create some complex copy/paste operations. It is especially helpful if you have complex rules that you don’t want to recreate in the new range or if you have a huge (i.e., database-like) spreadsheet that requires specific formatting or contains lots of embedded formulas.
Sometimes you get spreadsheets from coworkers and you really only need certain components. Now you can programatically copy the parts you like while eliminating the parts you don’t.
For more VBA tips, techniques, and tactics, subscribe to our VBA Insiders email series using the form below.
Once you subscribe, please share this article on Twitter and Facebook.
Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.
Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.
This article was written by Cory Sarver, a contributing writer for The VBA Tutorials Blog. Visit him on LinkedIn and his personal page.
Источник
PasteSpecial in VBA
In this article, we will see an outline on VBA PasteSpecial. When we work with data in excel some data are obtained by formulas. These formulas are from references and when we paste this data to another sheet or any other workbook what happens? Because the formula is a reference and the new sheet doesn’t have the reference for the formula the value pasted is shown as an error. So in these situations what we do is paste the values as special values and what it does is that it does not paste the formulas in the target worksheet rather than pasting the value generated by the formula in the target worksheet. Similarly, in VBA there is a method to paste the values which are known as Paste Special Method. We will learn in this article how to paste as values for a single cell to the entire column and then to paste in another worksheet also we will learn the difference of (.Value) and (.Paste)method.
How to Use the PasteSpecial Method in Excel VBA?
The following examples will teach us how to use the PasteSpecial method in Excel by using the VBA Code.
You can download this VBA PasteSpecial Excel Template here – VBA PasteSpecial Excel Template
Example #1 – VBA PasteSpecial
Let us begin with the basic step in this example when we paste special for a single cell in VBA. For this, follow the below steps:
Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.
Step 2: In the module start a subprocedure.
Code:
Sub Example1() End Sub
Step 3: Let us copy the value we have in cell A1 using the range property method.
Code:
Sub Example1() Range("A1").Copy End Sub
Step 4: Now let us use the paste special method to paste value we copied in cell B1.
Code:
Sub Example1() Range("A1").Copy Range("B1").PasteSpecial Paste:=xlPasteValues End Sub
Step 5: When we execute the above code we can see the result in the cell B1.
Example #2 – VBA PasteSpecial
In the previous example, we copied value from a cell and paste it to an adjacent cell. Now let us copy a value from a range and paste it to another sheet. In this example, we have a value in cell A1 which is in sheet 2 and we want to paste it in sheet 2 to cell B1. For this, follow the below steps:
Step 1: We will work in the same module we had inserted as Module1 and start our subprocedure as Example 2.
Code:
Sub Example2() End Sub
Step 2: Now let us copy the value from sheet 2 and cell A1 by using the paste method.
Code:
Sub Example2() Sheets("Sheet2").Range("A1").Copy End Sub
Step 3: The next step is to paste the values in sheet 3 using the paste special method in the cell B1.
Code:
Sub Example2() Sheets("Sheet2").Range("A1").Copy Sheets("Sheet3").Range("B1").PasteSpecial Paste:=xlPasteValues End Sub
Step 4: Before we run the above procedure let us check what we have as Value in Cell A1 for sheet 2
Step 5: Now run the code and see the result in sheet 3.
Example #3 – VBA PasteSpecial
Earlier we copied a cell from one cell to another and from one worksheet to another. In this example, we will copy an entire column and paste it to another column. For this, follow the below steps:
Step 1: The defining of the subprocedure will be the same as for all the codes above, let us begin right below the example 3 in the same module.
Code:
Sub Example3() End Sub
Step 2: Since we are working in sheet 4 now so it is necessary to activate sheet 4 before we make any changes to avoid confusion and error.
Code:
Sub Example3() Worksheets("Sheet4").Activate End Sub
Step 3: Now we will copy the values in column A using the copy method.
Code:
Sub Example3() Worksheets("Sheet4").Activate Columns("A").Copy End Sub
Step 4: And we will paste the copied column to column B using the paste special method.
Code:
Sub Example3() Worksheets("Sheet4").Activate Columns("A").Copy Columns("B").PasteSpecial Paste:=xlPasteValues End Sub
Step 5: Run this code by hitting F5 or the Run button. We can see that the values from column A have been copied and pasted to column B.
Example #4 – VBA PasteSpecial
Now we have some data in Sheet 5 as follows, which shows the percentage of marks obtained by the students. For this, follow the below steps:
Step 1: In the same module below example 3 we will declare our another procedure named as Example 4.
Code:
Sub Example4() End Sub
Step 2: Now let us activate sheet 5 first to use its properties.
Code:
Sub Example4() Worksheets("Sheet5").Activate End Sub
Step 3: Copy the entire range from A1 to D6 and paste it sheet 6 from cell A7 to D6 by the following code.
Code:
Sub Example4() Worksheets("Sheet5").Activate Sheets("Sheet5").Range("A1:D6").Copy Sheets("Sheet6").Range("A1:D6").PasteSpecial Paste:=xlPasteValues End Sub
Step 4: Run this code by hitting F5 or Run button. we get the following result in sheet 6.
We have seen in both the above examples in example 3 and example 4, when we paste the values the format is changed because the formulas are not pasted.
Let us look through both the example 3 and 4 in example 5 as follows.
Example #5 – VBA PasteSpecial
Code:
Sub Example5() Worksheets("Sheet4").Activate Columns("A").Copy Columns("B").PasteSpecial Paste:=xlPasteValuesAndNumberFormats Worksheets("Sheet5").Activate Sheets("Sheet5").Range("A1:D6").Copy Sheets("Sheet6").Range("A1:D6").PasteSpecial Paste:=xlPasteValuesAndNumberFormats End Sub
Now when we run the above code we can see the difference in our result for example 3 and 4 as follows:
Result for Example 3.
Result for Example 4.
This method not only copies and paste the values but also keep the formatting of the values intact.
Conclusion
We discussed above for example 3 and example 4 that the format for our result changes when we use the paste special method. In paste special method we have another option to paste numbers and formats. PasteSpecial is a type of worksheet function when we copy and right-click on any cell to paste the values we get three options one is the normal paste function other being paste values and one is the paste special. Similar to the worksheet function we have to paste special in VBA too. Paste special function can be used for wide ranges in VBA.
Things to Remember
There are few things which we need to remember in using a range variable:
- Paste Special is a worksheet function which is also used in VBA.
- Paste Special does not paste the formulas it only copies the value generated by the formulas.
- Paste special does not keep the original formatting.
- Paste Values and number formats in a type of Paste special also keeps the formatting of the numbers.
Recommended Articles
This is a guide to the VBA PasteSpecial. Here we discuss how to use the PasteSpecial Method in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA SendKeys
- VBA On Error Goto
- VBA Input
- VBA RGB
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