Специальная вставка (метод 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 |
I’m looking for a way to copy a range (copyrange exists from 11 columns and a variety of rows) from an other workbook and insert/paste values only in my primary workbook, underneath the data already there.
Just pasting is no issue, but because I don’t want it to overwrite the last (SUM-)line I want to INSERT the values. By my knowing there isn’t anything like InsertSpecial xlInsertValues.
So how can I insert entire empty rows based on the counted rows of the copied range and than paste the values only in columns «E» to «O»?
Some preconditions are:
- copyrange exist from 11 columns and a variety of rows
- I’m trying to avoid having to switch twice between the two documents. So I only want to open the extern workbook, copy the values, open my primary workbook en insert the copied data with blank cells left and right from the range.
This is what I’ve got so far. It all goes wrong at the Insert part, because it doesn’t paste/insert values only. Note that it’s only a part of a bigger code. Rng31 is the copied range in the extern workbook.
Dim Rng31 As Range
Set Rng31 = Rng21.Resize(Rng21.Rows.Count, Rng21.Columns.Count + 10)
Dim regels As Integer
regels = Rng31.Rows.Count
Rng31.Copy
Wbbase.Activate
Sheets(2).Activate
Dim onderste As Range
Set onderste = Range("E65536").End(xlUp).Offset(1, 0)
onderste.Insert shift:=xlDown
Selection.PasteSpecial xlPasteValues
Друзья, Есть такой простенький макрос. Как изменить его, чтобы он вставлял только значения ячеек а не формулы? Sub Button1_Click() |
|
McCinly Пользователь Сообщений: 278 |
Sub Button1_Click() |
McCinly Пользователь Сообщений: 278 |
Sub Button1_Click() Даже так |
{quote}{login=McCinly}{date=13.02.2010 03:27}{thema=}{post}Sub Button1_Click() Даже так{/post}{/quote} спасибо, но вот эта строчка не проходит |
|
McCinly Пользователь Сообщений: 278 |
Подчеркивание это перенос строки, его надо убрать. Выделяете ячейки для копирования потом ctrl-c, ставите куда надо жмете кнопку, вставляются значения. |
{quote}{login=McCinly}{date=13.02.2010 03:44}{thema=}{post}Подчеркивание это перенос строки, его надо убрать. Выделяете ячейки для копирования потом ctrl-c, ставите куда надо жмете кнопку, вставляются значения.{/post}{/quote} да нет… я не это имел ввиду )). Вы взгляните на верхний скрипт… он вот отсюда http://www.planetaexcel.ru/forum.php?thread_id=13439&forum_id=129&page_forum=lastpage&allnum_forum=0#post98825 |
|
Guest Гость |
#7 13.02.2010 15:56:39 {quote}{login=The_Prist}{date=13.02.2010 03:52}{thema=}{post}Sub Button1_Click() супер! надеюсь что это будет еще кому-то полезно кроме меня! |
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
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.
Данный код добавляет в контекстное меню ячейки два новых действия:
1. Вставить только значения;
2. Вставить значения с транспонированием.
Нижеуказанный макрос лучше всего поместить в «личную книгу макросов» (PERSONAL)
В модуль «ЭтаКнига» файла PERSONAL вставляем:
Private Sub Workbook_Open() MyComBars End sub
Также создаем новый модуль (в книге PERSONAL), в который помещаем следующий код:
Option Private Module Sub MyComBars() Application.CommandBars("cell").Reset 'возвращаем стандартный ComBars With Application.CommandBars("cell").Controls.Add(Type:=1, Before:=5) .OnAction = "PasteValues" ' назначаем кнопке макрос .Caption = "Вставить значения" End With With Application.CommandBars("cell").Controls.Add(Type:=1, Before:=6) .OnAction = "PasteTranspose" ' назначаем кнопке макрос .Caption = "Вставить с транспонированием" End With End Sub Sub PasteValues() On Error Resume Next Selection.PasteSpecial Paste:=xlPasteValues End Sub Sub PasteTranspose() On Error Resume Next Selection.PasteSpecial Paste:=xlPasteAll, Transpose:=True End Sub
by LightZ
- 22777 просмотров
Не получается применить макрос? Не удаётся изменить код под свои нужды?
Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.