Selection pastespecial vba excel

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

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

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

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

Содержание

  1. Selection.PasteSpecial method (Word)
  2. Syntax
  3. Parameters
  4. Remarks
  5. Example
  6. See also
  7. Support and feedback
  8. VBA Excel. Метод Range.PasteSpecial (специальная вставка)
  9. Метод Range.PasteSpecial
  10. Синтаксис
  11. Параметры специальной вставки
  12. Константы XlPasteType
  13. Константы XlPasteSpecialOperation
  14. Примеры
  15. Selection.PasteSpecial method (Word)
  16. Синтаксис
  17. Параметры
  18. Замечания
  19. Пример
  20. См. также
  21. Поддержка и обратная связь
  22. Метод Worksheet.PasteSpecial (Excel)
  23. Синтаксис
  24. Параметры
  25. Замечания
  26. Пример
  27. Поддержка и обратная связь

Selection.PasteSpecial method (Word)

Inserts the contents of the Clipboard.

Syntax

expression.PasteSpecial (IconIndex, Link, Placement, DisplayAsIcon, DataType, IconFileName, IconLabel)

expression Required. A variable that represents a Selection object.

Parameters

Name Required/Optional Data type Description
IconIndex Optional Variant If DisplayAsIcon is True, this argument is a number that corresponds to the icon you want to use in the program file specified by IconFilename. If this argument is omitted, this method uses the first (default) icon.
Link Optional Variant True to create a link to the source file of the Clipboard contents. The default value is False.
Placement Optional Variant Can be either of the WdOLEPlacement constants.
DisplayAsIcon Optional Variant True to display the link as an icon. The default value is False.
DataType Optional Variant A format for the Clipboard contents when they are inserted into the document. WdPasteDataType.
IconFileName Optional Variant If DisplayAsIcon is True, this argument is the path and file name for the file in which the icon to be displayed is stored.
IconLabel Optional Variant If DisplayAsIcon is True, this argument is the text that appears below the icon.

Unlike with the Paste method, with PasteSpecial you can control the format of the pasted information and (optionally) establish a link to the source file (for example, a Microsoft Excel worksheet). If you don’t want to replace the contents of the specified selection, use the Collapse method before you use this method. When you use this method, the selection does not expand to include the contents of the Clipboard.

Example

This example inserts the Clipboard contents at the insertion point as unformatted text.

See also

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 Excel. Метод Range.PasteSpecial (специальная вставка)

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

Метод Range.PasteSpecial

Синтаксис

Специальная вставка работает только с данными ячеек, скопированными в буфер обмена методом 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» активного листа, ячейки которого заполнены числами:

Источник

Selection.PasteSpecial method (Word)

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

Синтаксис

expression. PasteSpecial (IconIndex, Link, Placement, DisplayAsIcon, DataType, IconFileName, IconLabel)

выражение (обязательно). Переменная, представляющая объект Selection .

Параметры

Имя Обязательный или необязательный Тип данных Описание
IconIndex Необязательный Variant Если параметр DisplayAsIcon имеет значение True, этот аргумент представляет собой число, соответствующее значку, который вы хотите использовать в файле программы, заданном параметром IconFilename. Если этот аргумент опущен, этот метод использует первый значок (по умолчанию).
Link Необязательный Variant Значение true , чтобы создать ссылку на исходный файл содержимого буфера обмена. Значение по умолчанию — False.
Placement Необязательный Variant Может быть любой из констант WdOLEPlacement .
DisplayAsIcon Необязательный Variant Значение true , чтобы отобразить ссылку в виде значка. Значение по умолчанию — False.
DataType Необязательный Variant Формат для содержимого буфера обмена при его вставке в документ. WdPasteDataType.
IconFileName Необязательный Variant Если параметр DisplayAsIcon имеет значение True, этот аргумент является путем и именем файла, в котором хранится отображаемый значок.
IconLabel Необязательный Variant Если параметр DisplayAsIcon имеет значение True, этот аргумент представляет собой текст, который отображается под значком.

Замечания

В отличие от метода Paste , с помощью PasteSpecial можно управлять форматом вставленной информации и (при необходимости) установить ссылку на исходный файл (например, лист Microsoft Excel). Если вы не хотите заменять содержимое указанного выделенного фрагмента, перед использованием этого метода используйте метод Collapse . При использовании этого метода выделение не расширяется, чтобы включить содержимое буфера обмена.

Пример

В этом примере содержимое буфера обмена вставляется в точку вставки как неформатированный текст.

См. также

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

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

Источник

Метод 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 и обратная связь.

Источник

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

Понравилась статья? Поделить с друзьями:
  • Selection list in word
  • Selection goto vba word
  • Selection format vba excel
  • Selection excel все методы
  • Selection end vba excel