Vba excel метод paste
Range.Cut – это метод, который вырезает объект Range (диапазон ячеек) в буфер обмена или перемещает его в указанное место на рабочем листе.
Синтаксис
Параметры
Параметры | Описание |
---|---|
Destination | Необязательный параметр. Диапазон ячеек рабочего листа, в который будет вставлен (перемещен) вырезанный объект Range (достаточно указать верхнюю левую ячейку диапазона). Если этот параметр опущен, объект вырезается в буфер обмена. |
Для вставки на рабочий лист диапазона ячеек, вырезанного в буфер обмена методом Range.Cut, следует использовать метод Worksheet.Paste.
Метод Range.Copy
Range.Copy – это метод, который копирует объект Range (диапазон ячеек) в буфер обмена или в указанное место на рабочем листе.
Синтаксис
Параметры
Параметры | Описание |
---|---|
Destination | Необязательный параметр. Диапазон ячеек рабочего листа, в который будет вставлен скопированный объект Range (достаточно указать верхнюю левую ячейку диапазона). Если этот параметр опущен, объект копируется в буфер обмена. |
Метод Worksheet.Paste
Синтаксис
Метод Worksheet.Paste работает как с диапазонами ячеек, вырезанными в буфер обмена методом Range.Cut, так и скопированными в буфер обмена методом Range.Copy.
Параметры
Параметры | Описание |
---|---|
Destination | Необязательный параметр. Диапазон (ячейка), указывающий место вставки содержимого буфера обмена. Если этот параметр не указан, используется текущий выделенный объект. |
Link | Необязательный параметр. Булево значение, которое указывает, устанавливать ли ссылку на источник вставленных данных: True – устанавливать, False – не устанавливать (значение по умолчанию). |
В выражении с методом Worksheet.Paste можно указать только один из параметров: или Destination, или Link.
Для вставки из буфера обмена отдельных компонентов скопированных ячеек (значения, форматы, примечания и т.д.), а также для проведения транспонирования и вычислений, используйте метод Range.PasteSpecial (специальная вставка).
Примеры
Вырезание и вставка диапазона одной строкой (перемещение):
Вырезание ячеек в буфер обмена и вставка методом ActiveSheet.Paste:
Копирование и вставка диапазона одной строкой:
Копирование ячеек в буфер обмена и вставка методом ActiveSheet.Paste:
Копирование одной ячейки и вставка ее данных во все ячейки заданного диапазона:
18 комментариев для “VBA Excel. Вырезание, копирование и вставка ячеек (диапазонов)”
Странно, что не рассмотрено копирование ячеек, которые Cells.
Например, следующая строка копирует ячейку A1 в B2
а эта делает тоже самое, но демонстрирует,
как можно добавить размер и смещение:
Cells ( 1 , "A" ) . Resize ( 1 , 1 ) . Offset ( 0 , 0 ) . Copy Cells ( 2 , "B" ) . Resize ( 1 , 1 ) . Offset ( 0 , 0 )
Здравствуйте!
Скажите, как можно копировать на Лист 1, а вставить на Лист 2 диапазон ячеек целиком, либо отсортированный по 1 признаку диапазон(например по какому-то определенному значению, скажем, числу «500» в одном столбце Листа 1)?
Привет, Максим!
Вот пример сортировки таблицы по значению 500 в первом столбце на "Лист6" и копирования диапазона с "Лист6" на "Лист4" :
Спасибо большое, только я, наверно, неправильно описал ситуацию.
Сперва из эталонной таблицы Лист 1 копируем весь список на существующий Лист4.
Затем, пропускаем шапку, и, начиная со строки7, уже на Лист4 ищем строку, у которой в столбце 5 стоит число 500.
Вырезаем эту строку и вставляем на позицию строки 7. т.е первая после шапки.
Ищем следующую строку — вырезаем, потом вставляем на позицию строки 7+1=8 и т.д.
В итоге оставим только те строки, у которых в столбце 5 стоит число «500», остальные удаляются строки.
(пробовал менять местами строки в предыдущем коде, ошибок нет, копирует, переходит на лист 4, но строки на нем не удаляет, циклы пошагово проходят, но ничего не изменяется.)
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" активного листа, ячейки которого заполнены числами:
Copy Paste in VBA is similar to what we do in excel worksheet, like we can copy a value and paste it to another cell also we can use paste special to paste only the values, similarly in VBA we use the copy method with range property to copy a value from one cell to other and to paste the value we use the worksheet function paste special or paste method.
How to Copy Paste in VBA?
Below are some examples of how to copy-paste in excel using VBA.
The basic thing we do in excel is we copy, we cut, and we paste the data from one cell to another cell. It requires no special introduction as well. However, while learning VBA coding is important to understand the same concept in coding language. Copy Paste in VBA is the routine task we do in the day in day in excel. In order to copy first, we need to decide which cell to copy.
Assume you have the word “Excel VBA” in the cell A1.
Code:
Code:
After selecting the method, press the space key to see the argument of the Copy method.
It says Destination.
This is nothing, but where do you want to copy-paste values in VBA without selecting the PASTE method.
If we are pasting in the same sheet, we can select the cell by using the Range object. Let us say if we want to paste the value in B3 cell, we can put the destination as “Range(“B3”).”
Code:
This will copy the data from cell A1 and paste in cell B3.
We can also use the below method to paste the data.
Code:
First, we will copy & select the data from cell A1 and paste in cell B3.
Now, if we want to copy-paste the value from the different worksheets using VBA macro, then in the Destination argument, we need to reference the sheet name by using the WORKSHEETS object then mention the range of cells in that WORKSHEET. The below code will do the job.
Code:
If we want to copy the data from a particular sheet and want to paste in another particular sheet, we need to mention both the names of the sheets.
Firstly we need to mention the copying sheet.
Then in the Destination argument, we need to mention the targeted worksheet name and range of the cell.
So the code should like this.
Code:
We have seen how to copy from worksheet to another worksheet in the same workbook. But we can also do this from one workbook to another workbook.
Take a look at the below code.
Code:
Firstly it will copy the data from the worksheet “Sheet1” in the workbook “Book1.xlsx” from the cell A1.
Then it will activate the workbook “Book 2.xlsx”.
In the active workbook, it will select the worksheet “Sheet 2.”
Now in the active sheet, it will paste.
Alternative Way for using Copy-Paste in VBA
We have one more alternative way of having the data from one cell to another cell. Assume you have the word “Excel VBA” in the cell A1 and you need the same to come in cell B3.
One method we have seen is using the VBA copy and paste method. Now I will show you one of the alternative ways. Look at the below piece of code to understand.
Code:
The above says whatever the value is there in the cell A1 should be equal to the value in the cell B3.
Even though this is not a copy and paste method still adds more value to our coding knowledge.
Top Ways of VBA Copy and Paste as Values
Now we will see different ways of VBA copy and paste values. Assume you are in the cell A1 as shown in the below image.
Code:
OR
- If you want to copy the entire used range of the worksheet, you can use the below code.
Code:
This will copy the entire used range in the worksheet “Sheet1” and will paste the same in the worksheet “Sheet2.”
Recommended Articles
This has been a guide to VBA Copy Paste. Here we discuss the top ways to Copy and Paste in VBA along with examples & a downloadable excel template. Below are some useful excel articles related to VBA –
There 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.
Copy and paste is the most common thing we do day in day out in our workplace. In a regular spreadsheet, we don’t need any special introduction to it. In VBA programming, it is very important to understand the concept of the “PASTE” method to understand the program to progress to the next level.
Understand the VBA Paste Method by Recording a Macro
Now I will show you the method of copy and pasting from cell A1 to A3. Follow the below steps to record a macro.
Step 2: The moment you click on record macro, it will show you the name of the default macro. As of now, just click on OK.
Step 3: The moment you click on, ok, it starts recording the activities you do. The first thing you need to do is select the cell A1 to copy.
Step 4: Now press Ctrl + C to copy the selected cell.
Step 5: Now, select the cell A3 where we need to paste the copied value.
Step 6: Now, paste by pressing Ctrl + V.
Step 7: Now stop the recordings.
Go to a visual basic editor to see the recordings. Below is out recording.
The first thing we have done here is “we have selected the cell A1”, so the code for this activity is Range(“A1”) Select
The next activity is we have copied the cell A1. You can notice here is code is not Range(“A1”). Copy rather it says Selection. Copy, this is because the moment you select the cell, it becomes either an active cell or selection. So it is referred to as Selection. Copy.
The third activity was we have selected the cell A1 to paste, so the code is Range(“A3”). Select
The final activity is we have pasted the value in the cell. Here it says Active Sheet because the moment you select the cell it becomes an active cell of the active sheet. So the code is “ActiveSheet.Paste”
This is how the Paste method works in VBA.
Formula
Below is the formula for the VBA paste method:
You can refer to the other worksheet by name. If you want to paste in the same worksheet where you have copied, you can refer to the current sheet by “Active Sheet.”
Destination: After mentioning the worksheet name, we need to refer to the destination cell address. For example, if you want to paste in the worksheet “Sale Data,” and in the cell A5 to A10, then below is the sample code.
Worksheets(“Sales Data”).Range(“A5:A10”)
If you ignore this argument then whatever the active cell will be treated as the destination cell.
Link: If you wish to create a link to the copied range, then you can supply the argument as TRUE or else FALSE.
Examples of Paste Method in Excel VBA
Below are the examples of the Excel VBA Paste Method.
Now let’s see the usage of the VBA paste method in the same sheet. For example, a demonstration, I have few values from cell A1 to A5.
Now I want to copy this and paste in C1 to C5. Follow the below steps to write the code on your own.
Step 1: Before posting anything, the first thing we need to do is to copy the range of data. So copy the range from A1 to A5.
Code:
Step 2: After copying, we need to specify where we are pasting. To do this first, we need to specify the worksheet name. In this case, since we are pasting in the same sheet, use the Active Sheet object.
Code:
Step 3: After selecting the paste method, we need to specify the destination as well. So the destination will be Range C1 to C5.
Code:
Step 4: Now, I don’t want to create any link to this VBA paste method, so I am ignoring then the next argument.
Now run this code using the F5 key or manually, it will copy from A1 to A5 and will paste in C1 to C5.
If you look at the values from C1 to C5, these values areas are in a cell from A1 to A5. So this VBA paste method copies everything and pastes everything.
Now I will use the LINK argument to see how it works. For the LINK’s argument, I have provided TRUE.
Code:
This will create a link to the cell from A1 to A5.
So it has created a link. One notable missing is the formatting of the cells here. It has not pasted any formatting styles.
Copying from one worksheet to another sto sheet requires worksheet names. Assume you want to copy the data from the sheet “First Sheet,” and you want to paste in the sheet “Second Sheet” below is the way of referring the sheets.
Code:
This will copy data from A1 to A5 from the sheet name called “First Name,” then it will paste in the sheet “Second Sheet” in the range C1 to C5.
Recommended Articles
This has been a guide to VBA Paste. Here we learn how the Paste method works through Excel VBA Code along with practical examples and a downloadable template. Below you can find some useful excel VBA articles –
Copy & Paste isn’t the greatest job in the world. But copying and pasting with special options requires some kind of knowledge in VBA. This isn’t the straight forward process as the simple copy & paste. One of the important paste special methods Paste Special Methods Paste 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 is “Paste Values” in VBA.
How to Paste Values in Excel using VBA?
For example, look at the below worksheet image.
In cell B6, we have applied the formula to calculate the total sales values from B2 to B5 cells. Now, if I copy and paste the cell B6 to C6, I will not get the value of 22,761, but I will get the corresponding formula.
To carry out the same thing in VBA, we need coding knowledge. We will show you how to paste values using VBA. Follow the below steps.
Step 1: Copy the cell B6.
To copy the cell B6, use the code as Range (“B6”).Copy
Step 2: Select the destination cell. In this case, C6 cell.
As you can see after the copy, it asks, “Destination.” This is nothing but where do you want to paste, so select the “Destination” as Range (“C6”)
Code:
Step 3: Run the Code
Run this code we will get the B6 copy in C6.
We got only the formula here.
Step 4: Perform a Paste Special Method.
To perform the paste special method, let’s look at the below syntax of the paste special method.
In the paste special method, we have several methods. Based on the operation we are doing, we need to select the type accordingly.
To understand, let’s break the code into two lines.
The first one is copying cell B6.
Now in the next line, write the destination cell as Range (“C6”)
Now to access Paste Special Method put a dot and start typing the letter “P.”
In the above variety of options, select the “Paste Special” method.
After selecting the method, hit the space key to see the various paste special methods.
In this variety of options, select “xlPasteValues.”
After selecting the option, hit the tab key to auto select.
Code:
Step 5: Run the Code
Now run the code, we should get only the value of the cell B6 to the cell C6.
If you notice the worksheet after running the code, it is still in the copy mode only.
This will disable the cut copy mode after the paste special method is executed.
Paste special is easy but in terms of using this as part of a large code requires an advanced level of coding skills.
For example, look at the below image.
In the above image of the worksheet in column “F,” we have a total column, i.e., in F2, F5, F8, F11, and F14 cells.
Now my requirement is to copy each total cell from the respective cell and paste in the column “H” with respective cells.
Code:
This code with paste special option will perform the task of copying each total cell and paste in the column “H” with respective cells.
To paste values from one worksheet to another, we need to mention both the worksheet names. Below is an example of that.
Recommended Articles
This has been a guide to VBA Paste Values. Here we discuss the top 3 tips to paste values using paste special method in VBA along with examples and a downloadable excel template. Below are some useful excel articles related to VBA –
Читайте также: