Excel vba pastespecial xlpastevalues

Специальная вставка (метод 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


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 xlPasteValues

Maks1390

Дата: Воскресенье, 04.09.2016, 17:47 |
Сообщение № 1

Группа: Пользователи

Ранг: Новичок

Сообщений: 14


Репутация:

0

±

Замечаний:
0% ±


Excel 2013

Здравствуйте, данный код копирует нужные строки и вставляет их в определенные листы. Проблема в том, что вставляются данные вместе с формулами, как применить метод PasteSpecial xlPasteValues чтобы в дополнительные листы вставлялись только значения ячеек. Спасибо за помощь.
[vba]

Код

Sub Alex2323()
Dim i&, lstr&, k&, lstrSh&
Application.ScreenUpdating = False
lstr = Cells(Rows.Count, 1).End(xlUp).Row
k = Sheets.Count
For i = 2 To k
‘Исключить листы
    If i = 9 Or i = 10 Then GoTo 0
    Sheets(i).Activate
    Range(«A2:M500»).Clear
0:
Next
Sheets(1).Activate
For i = 2 To lstr

If Cells(i, 2) = «Новый» Or Cells(i, 2) = «Отменен» Or Cells(i, 2) = «Ожидание оплаты» Then GoTo 1
        ‘скопировать данные
        Cells(i, 1).Offset(, 1).Resize(, 13).Copy
        Sheets(Right(Cells(i, 1), 1) + 1).Activate
        lstrSh = Cells(Rows.Count, 1).End(xlUp).Row
        Cells(lstrSh + 1, 1).Activate
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Sheets(1).Activate
1:
Next
Application.ScreenUpdating = True
End Sub

[/vba]

Сообщение отредактировал Maks1390Воскресенье, 04.09.2016, 17:48

 

Ответить

buchlotnik

Дата: Воскресенье, 04.09.2016, 18:15 |
Сообщение № 2

Группа: Заблокированные

Ранг: Участник клуба

Сообщений: 3442


Репутация:

929

±

Замечаний:
20% ±


2010, 2013, 2016 RUS / ENG

заменить[vba][/vba]на[vba]

Код

.PasteSpecial Paste:=xlPasteValues

[/vba]

Сообщение отредактировал buchlotnikВоскресенье, 04.09.2016, 18:15

 

Ответить

Maks1390

Дата: Воскресенье, 04.09.2016, 18:26 |
Сообщение № 3

Группа: Пользователи

Ранг: Новичок

Сообщений: 14


Репутация:

0

±

Замечаний:
0% ±


Excel 2013

buchlotnik, уже изменял, не срабатывает. Ошибка Run-time error

 

Ответить

buchlotnik

Дата: Воскресенье, 04.09.2016, 18:55 |
Сообщение № 4

Группа: Заблокированные

Ранг: Участник клуба

Сообщений: 3442


Репутация:

929

±

Замечаний:
20% ±


2010, 2013, 2016 RUS / ENG

Maks1390, покажите в файле

 

Ответить

Maks1390

Дата: Воскресенье, 04.09.2016, 19:16 |
Сообщение № 5

Группа: Пользователи

Ранг: Новичок

Сообщений: 14


Репутация:

0

±

Замечаний:
0% ±


Excel 2013

Вот файл с примером

К сообщению приложен файл:

primer.xls
(73.5 Kb)

 

Ответить

buchlotnik

Дата: Воскресенье, 04.09.2016, 19:17 |
Сообщение № 6

Группа: Заблокированные

Ранг: Участник клуба

Сообщений: 3442


Репутация:

929

±

Замечаний:
20% ±


2010, 2013, 2016 RUS / ENG

а допёрло: [vba]

Код

Cells(lstrSh + 1, 1).Select
    Selection.PasteSpecial Paste:=xlPasteValues

[/vba]

К сообщению приложен файл:

0753831.xls
(70.0 Kb)

Сообщение отредактировал buchlotnikВоскресенье, 04.09.2016, 19:19

 

Ответить

Maks1390

Дата: Воскресенье, 04.09.2016, 19:21 |
Сообщение № 7

Группа: Пользователи

Ранг: Новичок

Сообщений: 14


Репутация:

0

±

Замечаний:
0% ±


Excel 2013

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

 

Ответить

buchlotnik

Дата: Воскресенье, 04.09.2016, 19:27 |
Сообщение № 8

Группа: Заблокированные

Ранг: Участник клуба

Сообщений: 3442


Репутация:

929

±

Замечаний:
20% ±


2010, 2013, 2016 RUS / ENG

дык [vba]

Код

Cells(lstrSh + 1, 1).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        Selection.PasteSpecial Paste:=xlPasteFormats

[/vba]

 

Ответить

Maks1390

Дата: Воскресенье, 04.09.2016, 19:30 |
Сообщение № 9

Группа: Пользователи

Ранг: Новичок

Сообщений: 14


Репутация:

0

±

Замечаний:
0% ±


Excel 2013

buchlotnik, хм, точно, спасибо за помощь!

 

Ответить

Maks1390

Дата: Воскресенье, 04.09.2016, 19:49 |
Сообщение № 10

Группа: Пользователи

Ранг: Новичок

Сообщений: 14


Репутация:

0

±

Замечаний:
0% ±


Excel 2013

Извиняюсь, сразу не подумал спросить. К скопированным данным возможно обратится и пересчитать нужные ячейки?
Пример:
Обратится к скопированным строкам — выбрать ячейки L:L и N:N — посчитать (L:L — N:N) и изменить значение N:N

Чтобы в дополнительные листы попали уже посчитанные значения.

Сообщение отредактировал Maks1390Воскресенье, 04.09.2016, 20:08

 

Ответить

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

VBA PasteSpecial

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:

VBA PasteSpecial Example1

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: In the module start a subprocedure.

Code:

Sub Example1()

End Sub

VBA PasteSpecial Example1-1

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

Range /property Method Example1-2

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

VBA PasteSpecial Example1-3

Step 5: When we execute the above code we can see the result in the cell B1.

VBA PasteSpecial Example 1-4

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

Subprocedure Example2-1

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

sheet 2 Example 2-2

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

Paste Example2-3

Step 4: Before we run the above procedure let us check what we have as Value in Cell A1 for sheet 2

VBA PasteSpecial Example 2

Step 5: Now run the code and see the result in sheet 3.

VBA PasteSpecial Example 2-4

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

VBA PasteSpecial Example 3-1

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

VBA PasteSpecial Example 3-2

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

VBA PasteSpecial Example 3-3

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

VBA PasteSpecial Example 3-4

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.

Sheet 4 Example 3-5

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:

Students Table Example 5-3

Step 1: In the same module below example 3 we will declare our another procedure named as Example 4.

Code:

Sub Example4()

End Sub

VBA PasteSpecial Example 4-1

Step 2: Now let us activate sheet 5 first to use its properties.

Code:

Sub Example4()

Worksheets("Sheet5").Activate

End Sub

VBA PasteSpecial Example 4-2

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

Range Example 4-3

Step 4: Run this code by hitting F5 or Run button. we get the following result in sheet 6.

VBA PasteSpecial Example 4-4

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

Number Formats Example 5-1

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.

VBA PasteSpecial Example5-2

Result for Example 4.

VBA PasteSpecial Example5-3

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:

  1. Paste Special is a worksheet function which is also used in VBA.
  2. Paste Special does not paste the formulas it only copies the value generated by the formulas.
  3. Paste special does not keep the original formatting.
  4. 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 –

  1. VBA SendKeys
  2. VBA On Error Goto
  3. VBA Input
  4. VBA RGB

Like this post? Please share to your friends:
  • Excel vba paste image
  • Excel vba listbox list
  • Excel vba paste formats
  • Excel vba for pivot table
  • Excel vba paste destination