Специальная вставка (метод 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 |
VBA or Visual Basic for Application is an integration of Microsoft’s VisualBasic with MS office applications such as MS Excel. VBA is run within the MS Office applications to build customized solutions and programs. These enhance the capabilities of those applications. Today we look at the important Paste Special feature of Excel and VBA. We assume that you have working knowledge of MS Excel and VBA. However, if you are not familiar with the concepts and commands of Microsoft Excel, we recommend that you go through our introductory VBA tutorial .
What is a Macro?
A Macro is a compact piece of code which is created to customize MS office applications. Macros are created in VBA, which is a subset of Visual Basic and specifically designed to be user friendly. Instead of manually, coding repetitive tasks, it is more efficient to call Macros whenever required. This saves time, effort and money. To learn more about macros, you can take this course on VBA macros.
MS Excel Paste Special Commands
Paste Special is one of the features of Microsoft Office suite. MS Excel permits you to paste only specific aspects of cell data by using the Paste Special Feature. For example, if you need the results of a formula, but not the formula itself, you can choose to paste only the values calculated as the result of the formula. Pastes Special command is used to paste a wide variety of data aspects. Note that the Paste Special option is not applicable to cut data. In order for it to work a cell or range of cells must be copied.
How to use Paste Special in Excel 2010
When you copy a cell or range of cells, and paste it in the destination area you have two methods. They are Paste and Paste Special. Simple Paste does not change anything. However, Paste Special offers a number of options. Here we look at all the options offered in Paste Special Command.
- All–This is similar to the conventional paste.
- Formulas- pastes all the text, numbers and formulas in the selected cell without their formatting.
- Values– This option converts formulas from the copied cell to their calculated values in the destination cell.
- Formats– Here the content is not copied, only the formatting is copied from the source cells to the destination cells.
- Comments– This option pastes only the notes from the source cells to the destination cells.
- Validation– The option pastes only the Data Validation commands into the destination cell range.
- All Using Source Theme- When you select this option the cell styles are also copied along with the other content.
- All Except Borders– The entire content and the formatting without any borders is pasted into the destination cell range.
- Column Widths– Here the column widths of the sources cells are applied to the destination cells.
- Formulas and Number Formats- Includes the number formats of the source cells to the destination cells.
- Values and Number Formats – Here two things happen. Firstly, formulas are converted to their calculated values in the destination cells. Also the number formats of the source are applied to the destination cells.
- All Merging– When you select this option, the conditional formatting of the source cells are applied to the destination cell range.
Mathematical Operations
Paste Special also offers to do some simple mathematical calculations based on the values in source cells and the values in the destination cell range.
- None– This is the default setting. In this no operation is performed.
- Add– The values of the source cells are added to the value(s) in the destination cell.
- Subtract– This option subtracts the values copied from the source cell, from the destination cells values.
- Multiply-This option multiplies the values copied with the values of the destination cells. The result is stored in the destination cell(s).
- Divide- This is similar to multiply option except that division is done instead of multiplication.
Other options of Paste Special:
- Skip Blanks– If this option is selected only the non-empty cells are pasted.
- Transpose– Select this option if you want to change the orientation of the pasted entries.
- Paste Link– Select this option to establish a link between the source and destination cells. Here when the values of the original cells are updated or changed, the values of the destination cells are also correspondingly updated.
To learn about other aspects of Excel 2010 VBA you can take this course.
Excel VBA PasteSpecialMethod
VBA PasteSpecial command pastes a range of cells from the clipboard in to the destination range of cells. The syntax of VBA PasteSpecial looks like this
expression .PasteSpecial(Paste, Operation, SkipBlanks, Transpose)
Where expression is a variable that represents a Range object.Let’s take a look at the various parameters of VBA PasteSpecial method. Note that the parameters are all optional.
Name |
Required/Optional |
Data Type |
Description |
Paste | Optional | XlPasteType | The specific part of the cell range to be pasted. |
Operation | Optional | XlPasteSpecialOperation | Initiates the paste operation. |
SkipBlanks | Optional | Variant | Trueto not paste blank cells in the range on the Clipboard into the destination range. The default value is False. |
Transpose | Optional | Variant | True to transpose rows and columns when the specified range is pasted.The default value is False. |
Example 1
This is a simple example which demonstrates VBA PasteSpecial Method:
With Worksheets("Sheet1") .Range("A1:A5").Copy .Range("D1:D5").PasteSpecial _ Operation:=xlPasteSpecialOperationAdd End With
The values in cells D1:D5 on Sheet 1 is replaced with the sum of the existing content and the contents of cells A1:A5.
To see how this actually works, try out this VBA macro course by Mr Excel.
Example 2: Create a Macro to paste values into a new worksheet
We assume that you know how to open and work on VBA editor. We also assume that you are familiar with Macros in Excel VBA. If not, we suggest that you read our tutorials on the same. Here we look a program to create a macro to paste values into a new worksheet.
Sub ExamplePasteSpecial() Dim ws As Worksheet, wb As Workbook Set ws = ActiveSheet Set wb = Workbooks.Add(xlWBATWorksheet) ws.Range("C5:L19").Copy wb.Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues wb.Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteFormats Application.CutCopyMode = False End Sub
In the program, we declare “ws” as variable of type Worksheet and “wb” as variable of type Workbook. The source cell range is C5: L19. Note that the PasteSpecial function is invoked twice. In the first invocation, only the values calculated by the formula are pasted into the destination range. In the second invocation, only the formatting is copied and not the content.
Example 3: To Copy a Selected Cell and Paste it into another Cell
Sub PasteSpecial1() Dim Sell_1As Range Dim NewRowAs Long Dim RngAs Range Application.ScreenUpdating = False NewRow = 401 Set Rng = Range("A1:A400") For Each Sell_1InRng Rows(Sell_1.Row & ":" &Sell_1.Row).Select Selection.Copy Rows(NewRow& ":" &NewRow).Select Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _ False, Transpose:=False Application.CutCopyMode = False NewRow = NewRow + 1 Next Sell_1 Range("A1").Select Application.ScreenUpdating = True End Sub
The PasteSpecial Function copies only the values to the destination cell range. No mathematical operations are performed, no blank cells are omitted and the transpose parameter is set to false. This is a classic example of using PasteSpecial Command in Excel VBA to create a Macro which automates the process.
Example 4: Excel VBA Macro to Copy, Paste Special Values
Frequently we use formulas to extract data on to a specific worksheet. Then we want to remove the formulas and just keep the data. For that you would copy your selection , right click, chose paste special, select values, click ok and finally hit the enter key to achieve the desired results. Alternatively you could use the programming code below and assign it into a Macro to perform all the six steps mentioned above with a simple mouse click.
Sub CopyPasteSpecVal_1() Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = False End Sub
In this program, the formulas are not copied. The destination cell range contains only the calculated values using the formulas. No blanks are skipped. The source cells are not transposed and no mathematical operations are done.
It does not make sense for programmers today to manually enter code and data. It is far better to have Macros to do this especially if the tasks are tedious and repetitive. The PasteSpecial function offers a number of useful options to paste data from the source range to the destination range. Use it wisely and benefit from its power. We hope this tutorial on Excel VBA Paste Special Method was informative. You can always learn more about Excel VBA with this awesome course from Infinite Skills.
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
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