Vba excel paste - Мир ПК
Fruitsekta.ru

Мир ПК
33 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Vba excel paste

VBA Paste

VBA Paste

VBA Paste works in the same manner as we do Copy/Cut and Paste in Excel. VBA Paste it the automated version of what we regularly do in regular excel work. Pasting data in any required location is the routine task. In order to perform this activity, we need to define the location from where we will pick the data and location where we will paste it.

How to Use Excel VBA Paste?

We will learn how to use a VBA Paste with few examples in Excel.

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more

VBA Paste – Example #1

Let’s consider any cell in excel which has some text. Here we have kept the text “VBA Paste” in cell B3 as shown below.

Follow the below steps to use VBA Paste.

Step 1: Now go to the VBA window and open a new Module from the Insert menu as shown below.

Step 2: Once we do that, we will get a blank module. In that start writing Subcategory. It is recommended to write subcategory in the name of the function which we are performing.

Code:

Step 3: Now first select the Range cell where we have the data which we need to copy. Here our Range cell is B3, followed by .Copy function. This copies the data in Range cell which we have selected.

Code:

Step 4: Now we need a destination cell where we need to paste this copied value. With the help of Destination command select the Range cell. Here we have selected cell D1, where we will see the value.

Code:

Step 5: Once done, compile the code and run it.

We will see the cell content of cell B3 is now copied and pasted in cell D3 as shown above.

VBA Paste- Example #2

Let’s consider another example of VBA Paste. For this go to the VBA window and open a module and then follow the below steps.

Step 1: Start writing Subcategory in the name of VBA Paste or in any other name as shown below.

Code:

Step 2: Here we will consider the same data or reference cell B3 which we have seen in example-1. Select the Range cell B3 followed by .Copy command. This will copy the data.

Code:

Step 3: Now select the range cell where we need to paste the copied data. Here we are selecting cells D1 to D3 unlike selecting only one cell as shown in example-1.

Code:

Step 4: Once we have copied the data and selected the cells where it needs to get pasted. Now select Paste command with the help of ActiveSheet function. This Activesheet allows the copied cell pasted in range cells.

Code:

Step 5: Now compile the code and run it. We will see, cell value from cell B3 will get pasted from cells D1 to D3.

VBA Paste- Example #3

Another method of VBA Paste is using the manual process which we do for copy and paste.

Follow the below steps:

Step 1: Write Subcategory of VBA Paste as shown below.

Code:

Step 2: It is better to give the sequence to Subcategory if you are writing multiple sets of codes in a single file. For pasting anything, first, we need to copy that data. Here we have selected Copy command.

Code:

Step 3: Now select the range or reference cell which we need to copy and paste. Here we have Cell D3 with data “VBA Paste” in it.

Code:

Step 4: Now in excel, we select the cells where we need to paste the data by manually or by Shift + Ctrl + Up/Down keys. Here also we will select the location of cells by End(xlUp) command for selecting the range of output cells.

Code:

Step 5: Now select the output cell range, here we have selected cells D1 to D3, where we will see the pasted data.

Code:

Step 6: As the function, we need to perform is paste function, so we need to activate the paste command in VBA by ActiveSheet command followed by dot(.) Paste.

Code:

Step 7: Now, at last, allow CutCopyMode application as FALSE which means are only Copying the data instead of cutting it as well from the reference cell.

Code:

Step 8: Before running the code put the cursor on Cell B3 first. Then compile the code and run it. We will see our data will get copied to cells D1 to D3.

VBA Paste- Example #4

There is another way to using VBA Paste in a single line of code.

Follow the below steps:

Step 1: Write the subcategory in the sequence and name of a performed function.

Code:

Step 2: Use Worksheets command and select the Sheet where we will work. Here our sheet name is “Sheet1”. We can use Workbook.Sheet(1) also for selecting “Sheet1” instead of this.

Code:

Step 3: Select the cell from where we will copy the data. Here our Range cell is B3 which has the same data as we have seen in the above examples.

Code:

Step 4: Now insert the Copy command after a dot(.) for copying the data from the selected Range cell.

Code:

Step 5: Now use Destination command to select the location where we will paste the copied data. For this select Worksheet as “Sheet1” which we did at the beginning of this example and select the Range cells anywhere in the same sheet. Here we have selected Range output cells from D1 to D3.

Code:

Step 6: Now Compile and run. We will the text “VBA Paste” from cell B3 will get copied and pasted in cells D1 to D3 as shown below.

Читать еще:  Getobject vba excel

Pros of Excel VBA Paste

  • Applying the first 2 examples are the easy and quickest way to apply VBA Paste.
  • For huge data where it is difficult to do multiple activities, there if we automate this kind of small function, that would save huge time to doing manual things.
  • There is no limit of copy and pasting the data.

Things to Remember

  • Use subcategory in such a way that if you are using multiple modules then putting the sequence in that will make easy for tracking and choosing the right macro.
  • Save excel file in Macro Enable Format so that written code will be preserved for next time of use.
  • If you are writing multiple lines of code it is recommended to compile the code line by line to find if there is an error in it.
  • It is recommended to put the cursor at cell B3 if you are using example-3.

Recommended Articles

This has been a guide to VBA Paste. Here we discussed VBA Paste and how to use Excel VBA Paste along with practical examples and downloadable excel template. You can also go through our other suggested articles –

All in One Software Development Bundle (600+ Courses, 50+ projects)

VBA Paste

Excel VBA Paste

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 “PASTE” method to understand the program to progress to the next level.

Understand VBA Paste Method by Recording a Macro

To start off the proceedings lets understand how the paste method works by recording a simple macro. I have entered a value in the cell A1 as shown in the below image.

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 1: Click on Record Macro under the excel developer tab.

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

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 active cell or selection. So it 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 VBA paste method:

An expression is nothing but what is the worksheet name you want to paste. To understand worksheet object better read our article on “VBA Worksheet”.

You can refer the other worksheet by name if you want to paste in the same worksheet where you have copied you can refer the current sheet by “Active Sheet”.

Destination: After mentioning the worksheet name, we need to refer 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 Excel VBA Paste Method.

Example #1 – Paste in Same Excel Worksheet

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 Active Sheet object.

Code:

Step 3: After selecting the paste method we need to specify the destination as well. So 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.

Читать еще:  Vba excel calculate

Now run this code using 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 are as it is 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 LINK 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.

Example #2 – Paste in Different Excel Worksheet

Copying from one worksheet to another sheet requires worksheet names. Assume you want to copy the data from 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.

You can download the VBA Paste Template here:- VBA Paste Excel Template

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 –

Excel VBA: Copy and Paste a Range

One of the most common action you’ll need to learn is copying and pasting a range of data. It’s very easy to do this manually. In normal data, we use either CTRL + C to copy a selection of data and then use CTRL + V to paste the selected data in the target cell. It’s just as easy to copy and paste via VBA.

Range.Copy method

Range.Copy Method is a very convenient Method to copy and paste Range to destination in one line of code. All the formatting and formulas will be copied and pasted.

Syntax

Destination is optional. If this argument is omitted, Microsoft Excel copies the range to the Clipboard. It returns Variant.

Example 1: Copy Range and paste to another worksheet

The below code copy Sheet1 A1 to Sheet2 B1.

If there are more than one Range to copy, you just need to specific the first Range of the destination.

Example 2: copy row

The below code copy from Sheet1 row 1:2 to Sheet2 row 6.

Note that if you copy a row to destination, the destination Range must be a Row or a Range in column A.

Example 3: copy row and paste to new inserted row

Example 4: copy column

The below code copy Sheet1 column A:B to Sheet2 column B:C (because it pastes at B1).

Example 5: copy multiple Range to a new Workbook

In case the copied Columns are not adjacent to each other, Set a Range to combine those Columns (or Rows).

The below code copy range1 and then paste to A1 of new workbook.

Example 6: destination argument omitted

The following code example inspects the value in column D for each row on Sheet1. If the value in column D equals A, the entire row is copied onto SheetA in the next empty row. If the value equals B, the row is copied onto SheetB.

Range.PasteSpecial method

When working with your spreadsheet, you likely often have to copy formulas and paste them as values. To do this in a macro, you can use the PasteSpecial method.

Syntax

It returns Variant.

Parameters

NameRequired/OptionalData typeDescription
PasteOptionalXlPasteTypeSpecifies the part of the range to be pasted.
OperationOptionalXlPasteSpecialOperationSpecifies how numeric data will be calculated with the destinations cells on the worksheet.
SkipBlanksOptionalVariantTrue to have blank cells in the range on the clipboard not be pasted into the destination range. The default value is False.
TransposeOptionalVariantTrue to transpose rows and columns when the range is pasted. The default value is False.
XlPasteType enumeration
NameValueDescription
xlPasteAll-4104Everything will be pasted.
xlPasteAllExceptBorders7Everything except borders will be pasted.
xlPasteAllMergingConditionalFormats14Everything will be pasted and conditional formats will be merged.
xlPasteAllUsingSourceTheme13Everything will be pasted using the source theme.
xlPasteColumnWidths8Copied column width is pasted.
xlPasteComments-4144Comments are pasted.
xlPasteFormats-4122Copied source format is pasted.
xlPasteFormulas-4123Formulas are pasted.
xlPasteFormulasAndNumberFormats11Formulas and Number formats are pasted.
xlPasteValidation6Validations are pasted.
xlPasteValues-4163Values are pasted.
xlPasteValuesAndNumberFormats12Values and Number formats are pasted.
XlPasteSpecialOperation enumeration
NameValueDescription
xlPasteSpecialOperationAdd2Copied data will be added to the value in the destination cell.
xlPasteSpecialOperationDivide5Copied data will divide the value in the destination cell.
xlPasteSpecialOperationMultiply4Copied data will multiply the value in the destination cell.
xlPasteSpecialOperationNone-4142No calculation will be done in the paste operation.
xlPasteSpecialOperationSubtract3Copied data will be subtracted from the value in the destination cell.

Example 1: paste values

Note: To remove the animation around the copied cell add below code:

Example 2: paste formats

Example 3: paste formulas

Example 4: EntireRow copy and paste

Example 5: Multiply

This example replaces the data in cells A1:C2 on Sheet1 with the multiply of the existing contents and cells D1 on Sheet1.

1
2
ABCD
1233
456

VBA Code

Result

1
2
ABCD
3693
121518

Example 6: Add

This example replaces the data in cells D1:D2 on Sheet1 with the sum of the existing contents and cells A1:A2 on Sheet1.

При вставке из VBA картинки на лист ошибка «Метод paste из класса worksheet завершен неверно»

Ничто в мире не идеально, и Excel тоже. Как и любая программа он порой может сильно удивлять разными «непонятками». Вот очередная шутка: казалось бы простой код по копированию и вставке картинки из листа Excel, который отлично работает в 2010, вылетает в 2016 с ошибкой Метод paste из класса worksheet завершен неверно :

Сам код простой и ошибки в общем-то вызывать не должен:

Sub CopyPastePicture() ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»).Copy ActiveWorkbook.Sheets(«MAIN»).Paste End Sub

При этом самое печально то, что это даже не на каждом ПК проявляется. А при пошаговой отладке кода и вовсе пропадает. Т.е. для получения ошибки недостаточно одного Excel 2016, здесь влияет несколько факторов: установленные программы, операционная система, метод выполнения и т.д. и т.п. Разбирать каждый частный случай не представляется возможным. Да и даже если найти причину — что, теперь надо удалять все лишнее, что не понравилось Excel-ю? А почему тогда это лишнее не мешает тому же коду в Excel 2010? А если этот код — часть программы на заказ? Заказчик скажет «Тыжпрограммист» и будет прав — это наша проблема, проблема разработчиков. Мы обязаны знать эти подводные камни или как минимум хоть уметь вовремя их устранять. Поэтому приходится искать обходные пути. Судя по ошибке, сам корень зла где-то по пути от буфера к Excel. Возможно, наша скопированная картинка просто не до конца «прогрузилась» в буфер и надо дождаться завершения этой прогрузки. Текст ошибки несколько укрепляет это предположение. Первый порыв — использовать DoEvents, чтобы передать эстафету операционной системе — дать ей завершить свои процессы, в том числе и обработку буфера обмена:

Sub CopyPastePicture() ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»).Copy DoEvents ActiveWorkbook.Sheets(«MAIN»).Paste End Sub

Но это не спасает ситуацию. Равно как не спас и цикл с сотней DoEvents:

Sub CopyPastePicture() Dim i As Long ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»).Copy For i = 1 To 100: DoEvents: Next ActiveWorkbook.Sheets(«MAIN»).Paste End Sub

С одной стороны все логично и должно работать. И даже работает, но не всегда — ошибка все равно появлялась чуть ли не в половине случаев. Почему? Потому что дело все же в некорректной работе буфера. И DoEvents хоть и передавал управление — проблемы вовсе не решал. Он просто давал небольшую отсрочку, которая позволяла в ряде случаев картинке догрузиться в буфер и избежать ошибки. Но главная проблема в том, что неизвестно для какого ПК сколько таких циклов надо, потому что неизвестно сколько ждать до полной загрузки картинки в буфер. Неизвестно, т.к. на каждом ПК это может быть разное время. В итоге, помучившись еще какое-то время я нашел «костыльное» решение проблемы через такой код:

Sub CopyPastePicture() ‘сначала очистим буфер, чтобы там точно ничего лишнего не было Application.CutCopyMode = False ‘копируем картинку ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»).Copy ‘а теперь разрешаем пропуск всех ошибок! On Error Resume Next Err.Clear ‘очищаем лог ошибок, если они были ‘пробуем вставить нашу картинку ActiveWorkbook.Sheets(«MAIN»).Paste ‘если в момент вставки возникла ошибка ‘ сработает цикл, который будет выполняться до тех пор, ‘ пока что-то все же не вставится Do While Err.Number <> 0 Err.Clear ActiveWorkbook.Sheets(«MAIN»).Paste ‘передаем управление системе DoEvents Loop ‘отключаем пропуск ошибок On Error GoTo 0 ‘опять очищаем буфер — теперь уже от того, что скопировали сами кодом Application.CutCopyMode = False End Sub

Решение основано на том, что мы сначала копируем картинку, а потом пробуем её вставить. Если возникает ошибка — запускаем цикл, в котором пытаемся вставить картинку из буфера до тех пор, пока она все же не будет вставлена. Т.е. пока ошибка возникает — картинка не прогрузилась и цикл работает. Как только картинка прогрузилась в буфер — она вставляется без ошибки и цикл завершается.
И такой подход работает и по скорости не сильно тормозит процесс. Единственное, что неплохо было бы добавить — так это некий счетчик. Вдруг по какой-то причин буфер вообще очистился(ну бывают системные ошибки) или ошибка возникала совсем по другой причине(например, вставка производится на защищенный лист) — тогда получим бесконечный цикл. В этом случае лучше всего код «обернуть» в функцию:

‘————————————————————————————— ‘ Author : The_Prist(Щербаков Дмитрий) ‘ http://www.excel-vba.ru ‘ info@excel-vba.ru ‘ Purpose: Копирует указанную картинку и вставляет на заданный лист ‘ oCopy — картинка, для вставки на лист ‘ wsPaste — лист, на который необходимо вставить картинку ‘————————————————————————————— Function CopyPastePicture(oCopy As Shape, wsPaste As Worksheet) Dim lPasteCnt As Long ‘счетчик вставок ‘сначала очистим буфер, чтобы там точно ничего лишнего не было Application.CutCopyMode = False ‘копируем картинку oCopy.Copy ‘а теперь разрешаем пропуск всех ошибок! On Error Resume Next Err.Clear ‘очищаем лог ошибок, если они были ‘пробуем вставить нашу картинку wsPaste.Paste ‘если в момент вставки возникла ошибка ‘ сработает цикл, который будет выполняться до тех пор, ‘ пока что-то все же не вставиться Do While Err.Number <> 0 Err.Clear wsPaste.Paste ‘передаем управление системе DoEvents ‘сччитаем кол-во вставок lPasteCnt = lPasteCnt + 1 ‘если уже более 1000 вставок сделали ‘ но ошибка не уходит — принудительно завершаем цикл ‘ ошибка при этом будет не нулевой If lPasteCnt > 1000 Then Exit Do End If Loop ‘если вставка прошла успешно — ошибка будет нулевой CopyPastePicture = (Err.Number = 0) ‘отключаем пропуск ошибок On Error GoTo 0 ‘опять очищаем буфер — теперь уже от того, что скопировали сами кодом Application.CutCopyMode = False End Function

тогда можно будет не только вставить картинку, но и получить обратную связь — успешно прошла вставка или нет. Если кажется, что 1000 попыток это много, то можно просто в строке If lPasteCnt > 1000 Then вместо 1000 указать нужное число.
А использовать приведенную функцию можно будет так:

Sub TryPastePicture() If CopyPastePicture(ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»), ActiveWorkbook.Sheets(«MAIN»)) = False Then MsgBox «Не удалось вставить картинку», vbInformation, «www.excel-vba.ru» Exit Sub End If End Sub

Т.е. мы вызываем функцию, которая пробует вставить картинку. Если все 1000 попыток были безуспешными, то функция вернет значение False . Если же хоть одна вставка удалась — функция вернет True .
Кстати, функция поможет сделать вставку не только картинки, но и любой другой фигуры, у которой есть метод Copy: рисунок, фигура, диаграмма.

Если тоже столкнулись с такой проблемой — делитесь в комментариях кто как решал и что помогло. Соберем подборку методов 🙂

Статья помогла? Поделись ссылкой с друзьями!

Ссылка на основную публикацию
Adblock
detector