Copy from clipboard vba excel

Работа с буфером обмена в VBA Excel: копирование и вставка ячеек, копирование текста из переменной, очистка буфера обмена. Объект DataObject. Примеры.

Копирование и вставка ячеек

Копирование содержимого и форматов ячеек (диапазона) в буфер обмена осуществляется методом Range.Copy, а вставка – методом Worksheet.Paste:

‘Копирование одной ячейки в буфер обмена

Range(«A10»).Copy

Cells(10, 1).Copy

‘Копирование диапазона ячеек в буфер обмена

Range(«B8:H12»).Copy

Range(Cells(8, 2), Cells(12, 8)).Copy

‘Вставка ячейки (диапазона) из буфера обмена на рабочий лист

ActiveSheet.Paste Range(«A20»)

ActiveSheet.Paste Cells(20, 1)

При вставке диапазона ячеек из буфера обмена на рабочий лист достаточно указать верхнюю левую ячейку места (диапазона) вставки.

Для вставки из буфера обмена отдельных компонентов скопированных ячеек (значения, формулы, примечания и т.д.), а также применения к диапазону транспонирования или вычислений, используется метод Range.PasteSpecial (специальная вставка).

Буфер обмена и переменная

Передача текста между переменной и буфером обмена в VBA Excel осуществляется с помощью объекта DataObject. Стоит иметь в виду, что на некоторых компьютерах DataObject может некорректно работать при открытом окне проводника.

Объект DataObject

DataObject – это область временного хранения форматированных фрагментов текста, используемая в операциях переноса данных.

Подробнее об элементе DataObject вы можете прочитать на сайте разработчиков.

Методы объекта DataObject:

Метод Описание
GetFromClipboard Копирует данные из буфера обмена в DataObject
GetText Извлекает текстовую строку из объекта DataObject в указанном формате
PutInClipboard Перемещает данные из DataObject в буфер обмена
SetText Копирует текстовую строку в DataObject, используя указанный формат

Копирование текста из переменной в буфер обмена

Sub Primer2()

Dim s As String, myData As New DataObject

s = «Копирование текста из переменной в буфер обмена»

‘Копируем текст из переменной в DataObject

myData.SetText (s)

‘Перемещаем текст из DataObject в буфер обмена

myData.PutInClipboard

‘Проверяем содержимое буфера обмена

ActiveSheet.Paste Range(«A1»)

End Sub

Копирование текста из буфера обмена в переменную

Sub Primer3()

Dim s As String, myData As New DataObject

Range(«A1») = «Копирование текста из буфера обмена в переменную»

‘Копируем данные из ячейки в буфер обмена

Range(«A1»).Copy

‘Копируем данные из буфера обмена в DataObject

myData.GetFromClipboard

‘Извлекаем текст из объекта DataObject и присваиваем переменной s

s = myData.GetText

‘Проверяем содержимое переменной s

MsgBox s

End Sub

Очистка буфера обмена

Специального метода для очистки буфера обмена в VBA Excel нет. Для решения этой задачи можно использовать выход из режима вырезания-копирования:

Application.CutCopyMode = False

Следующий пример демонстрирует вставку скопированной ячейки "A1" в ячейки "A2" и "A3" и отсутствие вставки в ячейки "A4" и "A5" после строки Application.CutCopyMode = False:

Sub Primer4()

Range(«A1») = «Очистка буфера обмена»

Range(«A1»).Copy

ActiveSheet.Paste Range(«A2»)

ActiveSheet.Paste Range(«A3»)

Application.CutCopyMode = False

On Error Resume Next

ActiveSheet.Paste Range(«A4»)

ActiveSheet.Paste Range(«A5»)

End Sub

Оператор On Error Resume Next необходим для обработки (пропуска) ошибки, возникающей при вставке из пустого буфера обмена.

Функции для работы с буфером обмена

В некоторых системах, начиная с Windows 8, метод DataObject.PutInClipboard не работает правильно: если открыт хотя бы один экземпляр Проводника (папка), в буфер обмена записываются два квадратика. Следующие функции должны решить эту проблему:

‘Функция записи текста в буфер обмена

Function SetClipBoardText(ByVal Text As Variant) As Boolean

    SetClipBoardText = CreateObject(«htmlfile»).parentWindow.clipboardData.SetData(«Text», Text)

End Function

‘Функция вставки текста из буфера обмена

Function GetClipBoardText() As String

    On Error Resume Next

    GetClipBoardText = CreateObject(«htmlfile»).parentWindow.clipboardData.GetData(«Text»)

End Function

‘Функция очистки буфера обмена

Function ClearClipBoardText() As Boolean

    ClearClipBoardText = CreateObject(«htmlfile»).parentWindow.clipboardData.clearData(«Text»)

End Function

Пример использования функций для работы с буфером обмена:

Sub Primer()

Dim s As String

    s = «Копирование текста из переменной в буфер обмена»

    ‘Копируем текст в буфер обмена

    SetClipBoardText (s)

    ‘Вставляем текс из буфера обмена в ячейку «A1»

    Range(«A1») = GetClipBoardText

    ‘Очищаем буфер обмена, если это необходимо

    ClearClipBoardText

End Sub


There is no built-in functionality in Excel to use the clipboard. We could have implemented the clipboard functionality from scratch using COM DataObject and Win32 API. To save time we will instead show you how to use the Microsoft Forms DataObject class.

There are two different ways to use the Microsoft Forms DataObject:

  1. Add a reference to the COM library FM20.dll (Microsoft Forms 2.0), or
  2. Use late binding by calling CreateObject

In most cases you don’t want to add a reference to the Microsoft Forms 2.0 COM library. It is messy to maintain for other developers, and if you re-use your code in another Excel Workbook you would have to remember to add the reference too. In this article we will show you have to use late binding which is enabled through the COM IDispatch interface.

Late binding

The correct way in VBA to create a new instance of a COM Object is to use the CreateObject method. In a perfect world we would have written a statement like

' Instance
Dim objDataObject As Object

' Allocate instance (DOES NOT WORK)
Set objDataObject = CreateObject("Microsoft.Forms.DataObject")

Unfortunately the above statement doesn’t work. This is because when we run Regsvr32 to install the FM20.dll library no named entries are registered in the registry. Instead we need to use the Class ID (CLSID) to find the object definition in the registry. The class ID (CLSID) for the Microsoft Forms 2.0 DataObject is “1C3B4210-F441-11CE-B9EA-00AA006B1A69”. To create a new instance of the DataObject we need to do the following

' Instance
Dim objDataObject As Object

' Allocate new instance of Microsoft Forms 2.0 DataObject
Set objDataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

The object definition of the Microsoft Forms DataObject can be found in the registry (regedit.exe). You can see that the CLSID refers to the FM20.dll.

Microsoft Form 2.0 DataObject in the registry
Microsoft Form 2.0 DataObject in the registry

To Copy any text to the clipboard we need to use the methods SetText and PutInClipboard. Copying text data to the clipboard requires two steps. The first step is to put the text in a DataObject variable, and then copy the entire DataObject to the clipboard. A DataObject can contain many different clipboard formats. Internally the text format is known as CF_TEXT and has the numeric value 1. If you would like to copy a Bitmap or a Metafile to the clipboard it is much more complicated, and it will not be covered in this article.

To Paste existing text from the clipboard, we need to call GetFromClipboard and GetText. First we need to retrieve a reference to the DataObject, and then we need to get the text. When pasting data from the clipboard, the Microsoft Forms DataObject works as a wrapper object. It is not the actual object stored on the clipboard. Instead it calls the methods of the OLE IDataObject interface of the clipboard object.

Code

The complete code for Copy and Paste in Excel can be found below:

' Copy Text To Clipboard
Public Sub SetClipboardText(ByVal strText As String)
    ' Instance
    Dim objDataObject As Object

    ' Allocate instance of Microsoft Forms DataObject
    Set objDataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

    ' Set the Properties
    With objDataObject
        ' Add text to the DataObject
        .SetText strText
        ' Copy all data in the DataObject to the Clipboard (internally calling OleSetClipboard)
        .PutInClipboard
    End With

    ' Free memory
    Set objDataObject = Nothing
End Sub

' Paste From Clipboard
Public Sub GetClipboardText() As String
    ' Instance
    Dim objDataObject As Object

    ' Allocate instance of Microsoft Forms DataObject
    Set objDataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

    ' Set the Properties
    With objDataObject
        ' Get the DataObject from the clipboard (internally calling OleGetClipboard)
        .GetFromClipboard
        ' Get the text and set the return value of the function
        GetClipboardText = .GetText
    End With

    ' Free memory
    Set objDataObject = Nothing
End Sub
    

Usage

The Copy and Paste methods can be called the following way:

' Example text
Dim strText As String

' Set the text
strText = "This is a test"

' Copy the text to the clipboard
Call SetClipboardText(strText)

' Get the text from the clipboard
strText = GetClipboardText()

Related

  • OleSetClipboard
  • OleGetClipboard
  • IDataObject
  • Standard Clipboard formats
  • Convert Column Index to Column Name in Excel
  • Get Microsoft Excel

Excel VBA Tutorial about how to copy paste cellsCopy and paste are 2 of the most common Excel operations. Copying and pasting a cell range (usually containing data) is an essential skill you’ll need when working with Excel VBA.

You’ve probably copied and pasted many cell ranges manually. The process itself is quite easy.

Well…

You can also copy and paste cells and ranges of cells when working with Visual Basic for Applications. As you learn in this Excel VBA Tutorial, you can easily copy and paste cell ranges using VBA.

However, for purposes of copying and pasting ranges with Visual Basic for Applications, you have a variety of methods to choose from.

My main objective with this Excel tutorial is to introduce to you the most important VBA methods and properties that you can use for purposes of carrying out these copy and paste activities with Visual Basic for Applications in Excel. In addition to explaining everything you need to know in order to start using these different methods and properties to copy and paste cell ranges, I show you 8 different examples of VBA code that you can easily adjust and use immediately for these purposes.

The following table of contents lists the main topics (and VBA methods) that I cover in this blog post. Use the table of contents to navigate to the topic that interests you at the moment, but make sure to read all sections 😉 .

Let’s start by taking a look at some information that will help you to easily modify the source and destination ranges of the sample macros I provide in the sections below (if you need to).

Scope Of Macro Examples In This Tutorial And How To Modify The Source Or Destination Cells

As you’ve seen in the table of contents above, this Excel tutorial covers several different ways of copying and pasting cells ranges using VBA. Each of these different methods is accompanied by, at least, 1 example of VBA code that you can adjust and use immediately.

All of these macro examples assume that the sample workbook is active and the whole operation takes place on the active workbook. Furthermore, they are designed to copy from a particular source worksheet to another destination worksheet within that sample workbook.

You can easily modify these behaviors by adjusting the way in which the object references are built. You can, for example, copy a cell range to a different worksheet or workbook by qualifying the object reference specifying the destination cell range.

Similar comments apply for purposes of modifying the source and destination cell ranges. More precisely, to (i) copy a different range or (ii) copy to a different destination range, simply modify the range references.

For example, in the VBA code examples that I include throughout this Excel tutorial, the cell range where the source data is located is referred to as follows:

Worksheets("Sample Data").Range("B5:M107")

This reference isn’t a fully qualified object reference. More precisely, it assumes that the copying and pasting operations take place in the active workbook.

The following reference is the equivalent of the above, but is fully qualified:

Workbooks("Book1.xlsm").Worksheets("Sample Data").Range("B5:M107")

This fully qualified reference doesn’t assume that Book1.xlsm is the active workbook. Therefore, the reference works appropriately regardless of which Excel workbook is active.

I explain how to work with object references in detail in The Essential Guide To Excel’s VBA Object Model And Object References. Similarly, I explain how to work with cell ranges in Excel’s VBA Range Object And Range Object References: The Tutorial for Beginners. I suggest you refer to these posts if you feel you need to refresh your knowledge about these topics, or if you’re not familiar with them. They will probably help you to better understand this Excel tutorial and how to modify the sample macros I include here.

You’ll also notice that within the VBA code examples that I include in this Excel tutorial, I always qualify the references up to the level of the worksheet. Strictly speaking, this isn’t always necessary. In fact, when implementing similar code in your VBA macros, you may want to modify the references by, for example:

  • Using variables.
  • Further simplifying the object references (not qualifying them up to the level of the worksheet).
  • Using the With… End With statement.

The reason I’ve decided to keep references qualified up to the level of the worksheet is because the focus of this Excel tutorial is on how to copy and paste using VBA. Not on simplifying references or using variables, which are topics I cover in separate blog posts, such as those I link to above (and which I suggest you take a look at).

The Copy Command In Excel’s Ribbon

Before we go into how to copy a range using Visual Basic for Applications, let’s take a quick look at Excel’s ribbon:

Perhaps one of the most common used buttons in the Ribbon is “Copy”, within the Home tab.

Excel Ribbon with Copy button

When you think about copying ranges in Excel, you’re probably referring to the action carried out by Excel when you press this button: copying the current active cell or range of cells to the Clipboard.

You may have noticed, however, that the Copy button isn’t just a simple button. It’s actually a split button:

I explain how you can automate the functions of both of these commands in this Excel tutorial. More precisely:

  • If you want to work with the regular Copy command, you’ll want to read more about the Range.Copy method, which I explain in the following section.
  • If you want to use the Copy as Picture command, you’ll be interested in the Range.CopyPicture method, which I cover below.

Let’s start by taking a look at…

Excel VBA Copy Paste With The Range.Copy Method

The main purpose of the Range.Copy VBA method is to copy a particular range.

When you copy a range of cells manually by, for example, using the “Ctrl + C” keyboard shortcut, the range of cells is copied to the Clipboard. You can use the Range.Copy method to achieve the same thing.

However, the Copy method provides an additional option:

Copying the selected range to another range. You can achieve this by appropriately using the Destination parameter, which I explain in the following section.

In other words, you can use Range.Copy for copying a range to either of the following:

  • The Clipboard.
  • A certain range.

The Range.Copy VBA Method: Syntax And Parameters

The basic syntax of the Range.Copy method is as follows:

expression.Copy(Destination)

“expression” is the placeholder for the variable representing the Range object that you want to copy.

The only parameter of the Copy VBA method is Destination. This parameter is optional, and allows you to specify the range to which you want to copy the copied range. If you omit the Destination parameter, the copied range is simply copied to the Clipboard.

This means that the appropriate syntax you should use for the Copy method (depending on your purpose) is as follows:

  • To copy a Range object to the Clipboard, omit the Destination parameter. In such a case, use the following syntax:
    expression.Copy
  • To copy the Range object to another (the destination) range, use the Destination parameter to specify the destination range. This means that you should use the following syntax:
    expression.Copy(Destination)

Let’s take a look at how you can use the Range.Copy method to copy and paste a range of cells in Excel:

Macro Examples #1 And #2: The VBA Range.Copy Method

This Excel VBA Copy Paste Tutorial is accompanied by an Excel workbook containing the data and macros I use. You can get immediate free access to this workbook by clicking the button below.

Get immediate free access to the Excel VBA Copy Paste workbook example

For this particular example, I’ve created the following table. This table displays the sales of certain items (A, B, C, D and E) made by 100 different sales managers in terms of units and total Dollar value. The first row (above the main table), displays the unit price for each item. The last column displays the total value of the sales made by each manager.

Sample table for Copy Paste VBA Excel

Macro Example #1: Copy A Cell Range To The Clipboard

First, let’s take a look at how you can copy all of the items within the sample worksheet (table and unit prices) to the Clipboard. The following simple macro (called “Copy_to_Clipboard”) achieves this:

Excel Macro Copy Paste Example #1

This particular Sub procedure is made out of the following single statement:

Worksheets("Sample Data").Range("B5:M107").Copy

This statement is made up by the following 2 items:

Let’s take a look at this macro in action. Notice how, once I execute the Copy_to_Clipboard macro, the copied range of cells is surrounded by the usual dashed border that indicates that the range is available for pasting.

After executing the macro, I go to another worksheet and paste all manually. As a last step, I autofit the column width to ensure that all the data is visible.

Practical example copy and paste with Excel macro

Even though the sample Copy_to_Clipboard macro does what it’s supposed to do and is a good introduction to the Range.Copy method, it isn’t very powerful. It, literally, simply copies the relevant range to the Clipboard. You don’t really need a macro to do only that.

Fortunately, as explained above, the Range.Copy method has a parameter that allows you to specify the destination of the copied range. Let’s use this to improve the power of the sample macro:

Macro Example #2: Copy A Cell Range To A Destination Range

The following sample Sub procedure (named “Copy_to_Range”) takes the basic Copy_to_Clipboard macro used as example #1 above and adds the Destination parameter.

Excel VBA Copy Paste macro example #2

Even though it isn’t the topic of this Excel tutorial, I include an additional statement that uses the Range.AutoFit method.

Range.AutoFit method in Excel macro example

Let’s take a closer look at each of the lines of code within this sample macro:

Line #1: Worksheets(“Sample Data”).Range(“B5:M107”).Copy

This is, substantially, the sample “Copy_to_Clipboard” macro which I explain in the section above.

More precisely, this particular line uses the Range.Copy method for purposes of copying the range of cells cells B5 and M107 of the worksheet called “Sample Data”.

However, at this point of the tutorial, our focus isn’t in the Copy method itself but rather in the Destination parameter which appears in…

Line #2: Destination:=Worksheets(“Example 2 – Destination”).Range(“B5:M107”)

You use the Destination parameter of the Range.Copy method for purposes of specifying the destination range in which to which the copied range of cells should be copied. In this particular case, the destination range is cells B5 to M107 of the worksheet named “Example 2 – Destination”, as shown in the image below:

Destination parameter of Range.Copy method in example

As I explain above, you can easily modify this statement for purposes of specifying a different destination. For example, for purposes of specifying a destination range in a different Excel workbook, you just need to qualify the object reference.

Line #3: Worksheets(“Example 2 – Destination”).Columns(“B:M”).AutoFit

As anticipated above, this statement isn’t absolutely necessary for the sample macro to achieve its main purpose of copying the copied range in the destination range. Its purpose is solely to autofit the column width of the destination range.

For these purposes, I use the Range.Autofit method. The syntax of this method is as follows:

expression.AutoFit

In this particular case, “expression” represents a Range object, and must be either (i) a range of 1 or more rows, or (ii) a range of 1 or more columns. In the Copy_to_Range macro example, the Range object is columns B through M of the worksheet titled “Example 2 – Destination”. The following image shows how this range is specified within the VBA code.

Excel VBA Copy Paste macro example with AutoFit

The following image shows the results obtained when executing the Copy_to_Range macro. Notice how this worksheet looks substantially the same as the source worksheet displayed above.

Sample table copied with VBA in Excel

If you were to compare the results obtained when copying a range to the Clipboard (example #1) with the results obtained when copying the range to a destination range (example #2), you may conclude that the general rule is that one should always use the Destination parameter of the Copy method.

To a certain extent, this is generally true and some Excel authorities generally discourage using the Clipboard. However, the choice between copying to the Clipboard or copying to a destination range isn’t always so straightforward. Let’s take a look at why this is the case:

The Range.Copy VBA Method: When To Copy To The Clipboard And When To Use The Destination Parameter

In my opinion, if you can achieve your purposes without copying to the Clipboard, you should simply use the Destination parameter of the Range.Copy method.

Using the Destination parameter is, generally, more efficient that copying to the Clipboard and then using the Range.PasteSpecial method or the Worksheet.Paste method (both of which I explain below). Copying to the Clipboard and pasting (with the Range.PasteSpecial or Worksheet.Paste methods) involves 2 steps:

  1. Copying.
  2. Pasting.

This 2-step process (usually):

  • Increases the procedure’s memory requirements.
  • Results in (slightly) less efficient procedures.

I explain this argument further in example #4 below, which introduces the Worksheet.Paste method. The Worksheet.Paste method is one of the VBA methods you’d use for purposes of pasting the data that you’ve copied to the Clipboard with the Range.Copy method.

Avoiding the Clipboard whenever possible may be a good idea to reduce the risks of data loss or leaks of information whenever another application is using the Clipboard at the same time. Some users report unpredictable Clipboard behavior in certain cases.

Considering this arguments, you probably understand why I say that, if you can avoid the Clipboard, you probably should.

However, using the Range.Copy method with the Destination parameter may not be the most appropriate solution always. For purposes of determining when the Destination parameter allows you to achieve the purpose you want, it’s very important that you’re aware of how the Range.Copy method works, particularly what it can (and can’t do). Let’s see an example of what I mean:

If you go back to the screenshots showing the results of executing the sample macros #1 (Copy_to_Clipboard) and #2 (Copy_to_Range), you’ll notice that the end result is that the destination worksheet looks pretty much the same as the source worksheet.

In other words, Excel copies and pastes all (for ex., values, formulas, formats).

In some cases, this is precisely what you want. However:

In other cases, this is precisely what you don’t want. Take a look, for example, at the following Sub procedure:

VBA code to copy and paste with error modification

At first glance, this is the Copy_to_Range macro that I introduce and explain in the section above. Notice, however, that I’ve changed the Destination parameter. More precisely, in this version of the Copy_to_Range macro, the top-left cell of the destination range is cell B1 (instead of B5, as it was originally) of the “Example 2 – Destination” worksheet.

Example of macro to copy and paste with change in destination

The following GIF shows what happens when I execute this macro. The worksheet shown is the destination “Example 2 – Destination” worksheet, and I’ve enabled iterative calculations (I explain to you below why I did this).

Macro copying and pasting cells in wrong destination

As you can see immediately, there’s something wrong. The total sales for all items are, clearly, inaccurate.

Result of macro with wrong copy destination

The reason for this is that, in the original table, I used mixed references in order to refer to the unit prices of the items. Notice, for example, the formula used to calculate the total sales of Item A made by Sarah Butler (the first Sales Manager in the table):

Excel formula with mixed reference

These formulas aren’t a problem as long as the destination cells are exactly the same as the source cells. This is the case in both examples #1 and #2 above where, despite the worksheet changing, the destination continues to be cells B5 to M107. That guarantees that the mixed references continue to point to the right cell.

However, once the destination range changes (as in the example above), the original mixed references wreak havoc on the worksheet. Take a look, for example, at the formula used to calculate the total sales of Item B by Sales Manager Walter Perry (second in the table):

Example of Excel formula with mixed circular reference

The formula doesn’t use the unit price of Item B (which appears in cell F1) to calculate the sales. Instead, it uses cell F5 as a consequence of the mixed references copied from the source worksheet. This results in (i) the wrong result and (ii) a circular reference.

By the way, if you’re downloading the sample workbook that accompanies this Excel tutorial, it will have circular references.

In such (and other similar) cases, you may not want to rely solely on the Range.Copy method with the Destination parameter. In other words: There are cases where you don’t want to copy and paste all the contents of the source cell range. There are, for example, cases where you may want to:

  • Copy a cell range containing formulas; and
  • Paste values in the destination cell range.

This is precisely what happens in the case of the example above. In such a situation, you may want to paste only the values (no formulas).

For purposes of controlling what is copied in a particular destination range when working with VBA, you must understand the Range.PasteSpecial method. Let’s take a look at it:

Excel VBA Copy Paste With The Range.PasteSpecial Method

Usually, whenever you want to control what Excel copies in a particular destination range, you rely on the Paste Special options. You can access these options, for example, through the Paste Special dialog box.

Paste Special dialog box in Excel

When working with Visual Basic for Applications, you usually rely on the Range.PasteSpecial method for purposes of controlling what is copied in the destination range.

Generally speaking, the Range.PasteSpecial method allows you to paste a particular Range object from the Clipboard into the relevant destination range. This, by itself, isn’t particularly exciting.

The power of the Range.PasteSpecial method comes from its parameters, and the ways in which they allow you to further determine the way in which Excel carries out the pasting. Therefore, let’s take a look at…

The Range.PasteSpecial VBA Method: Syntax And Parameters

The basic syntax of the Range.PasteSpecial method is as follows:

expression.PasteSpecial(Paste, Operation, SkipBlanks, Transpose)

“expression” represents a Range object. The PasteSpecial method has 4 optional parameters:

  • Parameter #1: Paste.
  • Parameter #2: Operation.
  • Parameter #3: SkipBlanks.
  • Parameter #4: Transpose.

Notice how each of these parameters roughly mimics most of the different sections and options of the Paste Special dialog box shown above. The main exception to this general rule is the Paste Link button.

Paste Special dialog with Paste Link button

I explain how you can paste a link below.

For the moment, let’s take a closer look at each of these parameters:

Parameter #1: Paste

The Paste parameter of the PasteSpecial method allows you to specify what is actually pasted. This parameter is the one that, for example, allows you specify that only the values (or the formulas) should be pasted in the destination range.

This is, roughly, the equivalent of the Paste section in the Paste Special dialog box shown below:

Paste Special dialog with Paste parameters

The Paste parameter can take any of 12 values that are specified in the XlPasteType enumeration:

Parameter #2: Operation

The Operation parameter of the Range.PasteSpecial method allows you to specify whether a mathematical operation is carried out with the destination cells. This parameter is roughly the equivalent of the Operation section of the Paste Special dialog box.

Operation options within Paste Special dialog box

The Operation parameter can take any of the following values from the XlPasteSpecialOperation enumeration:

Parameter #3: SkipBlanks

You can use the SkipBlanks parameter of the Range.PasteSpecial method to specify whether the blank cells in the copied range should be (or not) pasted in the destination range.

Paste Special dialog with Skip blanks

SkipBlanks can be set to True or False, as follows:

  • If SkipBlanks is True, the blank cells within the copied range aren’t pasted in the destination range.
  • If SkipBlanks is False, those blank cells are pasted.

False is the default value of the SkipBlanks parameter. If you omit SkipBlanks, the blank cells are pasted in the destination range.

Parameter #4: Transpose

The Transpose parameter of the Range.PasteSpecial VBA method allows you to specify whether the rows and columns of the copied range should be transposed (their places exchanged) when pasting.

Paste Special dialog with Transpose option

You can set Transpose to either True or False. The consequences are as follows:

  • If Transpose is True, rows and columns are transposed when pasting.
  • If Transpose is False, Excel doesn’t transpose anything.

The default value of the Transpose parameter is False. Therefore, if you omit it, Excel doesn’t transpose the rows and columns of the copied range.

Macro Example #3: Copy And Paste Special

Let’s go back once more to the sample macros and see how we can use the Range.PasteSpecial method to copy and paste the sample data.

The following sample Sub procedure, called “Copy_PasteSpecial” shows 1 of the many ways in which you can do this:

Example macro to copy and paste special

When using the Range.Copy method to copy to the Clipboard (as in the case above) you can end the macro with the statement “Application.CutCopyMode = False”, which I explain in more detail towards the end of this blog post. This particular statement cancels Cut or Copy mode and removes the moving border.

Let’s take a look at each of the lines of code to understand how this macro achieves its purpose:

Line #1: Worksheets(“Sample Data”).Range(“B5:M107”).Copy

This statement appears in both of the previous examples.

As explained in those previous sections, its purpose is to copy the range between cells B5 and M107 of the worksheet named “Sample Data” to the Clipboard.

Lines #2 Through #6 Worksheets(“Example 3 – PasteSpecial”).Range(“B5”).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlPasteSpecialOperationNone, SkipBlanks:=False, Transpose:=True

These lines of code make reference to the Range.PasteSpecial method that I explain in the previous section. In order to take a closer look at it, let’s break down this statement into the following 6 items:

Macro example with Range.PasteSpecial method

And let’s take a look at each of the items separately:

  • Item #1: “Worksheets(“Example 3 – PasteSpecial”).Range(“B5″)”.
    • This is a Range object. Within the basic syntax of the PasteSpecial method that I introduce above, this item is the “expression”.
    • This range is the destination range, where the contents of the Clipboard are pasted. In this particular case, the range is identified by its worksheet (“Example 3 – PasteSpecial” of the active workbook) and the upper-left cell of the cell range (B5).
    • To paste the items that you have in the Clipboard in a different workbook, simply qualify this reference as required and explained above.
  • Item #2: “PasteSpecial”.
    • This item simply makes reference to the Range.PasteSpecial method.
  • Item #3: “Paste:=xlPasteValuesAndNumberFormats”.
    • This is the Paste parameter of the PasteSpecial method. In this particular case, the argument is set to equal xlPasteValuesAndNumberFormats. The consequence of this, as explained above, is that only values and number formats are pasted. Other items, such as formulas and borders, aren’t pasted in the destination range.
  • Item #4: “Operation:=xlPasteSpecialOperationNone”.
    • The line sets the Operation parameter of the Range.PasteSpecial method to be equal to xlPasteSpecialOperationNone. As I mention above, this means that Excel carries out no calculation when pasting the contents of the Clipboard.
  • Item #5: “SkipBlanks:=False”.
    • This line confirms that the value of the SkipBlanks parameter is False (which is its default value anyway). Therefore, if there were blank cells in the range held by the Clipboard, they would be pasted in the destination.
  • Item #6: “Transpose:=True”.
    • The final parameter of the Range.PasteSpecial method (Transpose) is set to True by this line. As a consequence of this, rows and columns are transposed upon being pasted.

The purpose of this code example is just to show you some of the possibilities that you have when working with the Range.PasteSpecial VBA method. It doesn’t mean it’s how I would arrange the data it in real life. For example, if I were implementing a similar macro for copying similarly organized data, I wouldn’t transpose the rows and columns (you can see how the transposing looks like in this case further below).

In any case, since the code includes all of the parameters of the Range.PasteSpecial method, and I explain all of those parameters above, you shouldn’t have much problem making any adjustments.

Line #7: Worksheets(“Example 3 – PasteSpecial”).Columns(“B:CZ”).AutoFit

This line is substantially the same as the last line of code within example #2 above (Copy_to_Range). Its purpose is exactly the same:

This line uses the Range.AutoFit method for purposes of autofitting the column width.

The only difference between this statement and that in example #2 above is the column range to which it is applied. In example #2 (Copy_to_Range) above, the autofitted columns are B to M (Range(“B5:M107”)). In this example #3 (Copy_PasteSpecial), the relevant columns are B to CZ (Columns(“B:CZ”)).

The reason why I make this adjustment is the layout of the data and, more precisely, the fact that the Copy_PasteSpecial macro transposes the rows and columns. This results in the table extending further horizontally.

The following screenshot shows the results of executing the Copy_PasteSpecial macro. Notice, among others, how (i) no borders have been pasted (a consequence of setting the Paste parameter to xlPasteValuesAndNumberFormats), and (ii) the rows and columns are transposed (a consequence of setting Transpose to equal True).

Results of macro to copy and paste with transpose

If you only need to copy values (the equivalent of setting the Paste parameter to xlPasteValues) or formulas (the equivalent of setting the Paste parameter to xlPasteFormulas), you may prefer to set the values or the formulas of the destination cells to be equal to that of the source cells instead of using the Range.Copy and Range.PasteSpecial methods. I explain how you can do this (alongside an example) below.

As you can see, you can use the PasteSpecial method to replicate all of the options that appear in the Paste Special dialog box, except for the Paste Link button that appears on the lower left corner of the dialog.

Paste Special dialog with Paste Link

Let’s take a look at a VBA method you can use for these purposes:

Excel VBA Copy Paste With The Worksheet.Paste Method

The Worksheet.Paste VBA method (Excel VBA has no Range.Paste method) is, to a certain extent, very similar to the Range.PasteSpecial method that I explain in the previous section. The main purpose of the Paste method is to paste the contents contained by the Clipboard on the relevant worksheet.

However, as the following section makes clear, there are some important differences between both methods, both in terms of syntax and functionality. Let’s take a look at this:

Worksheet.Paste VBA Method: Syntax And Parameters

The basic syntax of the Worksheet.Paste method is:

expression.Paste(Destination, Link)

The first difference between this method and the others that I explain in previous sections is that, in this particular case, “expression” stands for a Worksheet object. In other cases we’ve seen in this Excel tutorial (such as the Range.PasteSpecial method), “expression” is a variable representing a Range object.

The Paste method has the following 2 optional parameters. They have some slightly particular conditions which differ from what we’ve seen previously in this same blog post.

  • Destination: Destination is a Range object where the contents of the Clipboard are to be pasted.
    • Since the Destination parameter is optional, you can omit it. If you omit Destination, Excel pastes the contents of the Clipboard in the current selection. Therefore, if you omit the argument, you must select the destination range before using the Worksheet.Paste method.
    • You can only use the Destination argument if 2 conditions are met: (i) the contents of the Clipboard can be pasted into a range, and (ii) you’re not using the Link parameter.
  • Link: You use the Link parameter for purposes of establishing a link to the source of the pasted data. To do this, you set the value to True. The default value of the parameter is False, meaning that no link to the source data is established.
    • If you’re using the Destination parameter when working with the Worksheet.Paste method, you can’t use the Link parameter. Macro example #5 below shows how one way in which you can specify the destination for pasting links.

Let’s take a look at 2 examples that show the Worksheet.Paste method working in practice:

Macro Example #4: Copy And Paste

The following sample macro (named “Copy_Paste”) works with exactly the same data as the previous examples. It shows how you can use the Worksheet.Paste method for purposes of copying and pasting data.

Macro example to copy and paste in Excel

Just as with the previous example macro #3, since this particular macro uses the Clipboard, you can add the statement “Application.CutCopyMode = False” at the end of the macro for purposes of cancelling the Cut or Copy mode. I explain this statement in more detail below.

Let’s take a look at each of the lines of code to understand how this sample macro proceeds:

Line #1: Worksheets(“Sample Data”).Range(“B5:M107”).Copy

This statement is the same as the first statement of all the other sample macros that I’ve introduced in this blog post. I explain its different items the first time is used.

Its purpose is to copy the contents within cells B5 to M107 of the “Sample Data” worksheet to the Clipboard.

Lines #2 And #3: Worksheets(“Example 4 – Paste”).Paste Destination:=Worksheets(“Example 4 – Paste”).Range(“B5:M107”)

This statement uses the Worksheet.Paste method for purposes of pasting the contents of the Clipboard (determined by line #1 above) in the destination range of cells.

To be more precise, let’s break down the statement into the following 3 items:

Sample macro code to copy and paste in Excel

  • Item #1: “Worksheets(“Example 4 – Paste”)”.
    • This item represents the worksheet named “Example 4 – Paste”. Within the basic syntax of the Worksheet.Paste method that I explain above, this is the expression variable representing a Worksheet object.
    • You can easily modify this object reference by, for example, qualifying it as I introduce above. This allows you to, for example, paste the items that are in the Clipboard in a different workbook.
  • Item #2: “Paste”.
    • This is the Paste method.
  • Item #3: “Destination:=Worksheets(“Example 4 – Paste”).Range(“B5:M107″)”.
    • The last item within the statement we’re looking at is the Destination parameter of the Worksheet.Paste method. In this particular case, the destination is the range of cells B5 to M107 within the worksheet named “Example 4 – Paste”.

Line #4: Worksheets(“Example 4 – Paste”).Columns(“B:M”).AutoFit

This is an additional line that I’ve added to most of the sample macros within this Excel tutorial for presentation purposes. Its purpose is to autofit the width of the columns within the destination range.

I explain this statement it in more detail above.

The end result of executing the sample macro above (Copy_Paste) is as follows:

Excel VBA Copy Paste table result

These results are substantially the same as those obtained when executing the macro in example #2 above (Copy_to_Range), which only used the Range.Copy method with a Destination parameter. Therefore, you may not find this particular application of the Worksheet.Paste method particularly interesting.

In fact, in such cases, you’re probably better off by using the Range.Copy method with a Destination parameter instead of using the Worksheet.Paste method (as in this example). The main reason for this is that the Range.Copy method is more efficient and faster.

The Worksheet.Paste method pastes the Clipboard contents to a worksheet. You must (therefore) carry out a 2-step process (to copy and paste a cell range):

  1. Copy a cell range’s contents to the Clipboard.
  2. Paste the Clipboard’s contents to a worksheet.

If you use the macro recorder for purposes of creating a macro that copies and pastes a range of cells, the recorded code generally uses the Worksheet.Paste method. Recorded code (usually) follows a 3-step process:

  1. Copy a cell range’s contents to the Clipboard.
  2. Select the destination cell range.
  3. Paste the Clipboard’s contents to the selected (destination) cell range.

You can (usually) achieve the same result in a single step by working with the Range.Copy method and its Destination parameter. As a general rule, directly copying to the destination cell range (by using the Range.Copy method with a Destination parameter) is more efficient than both of the following:

  • Copying to the Clipboard and pasting from the Clipboard.
  • Copying to the Clipboard, selecting the destination cell range, and pasting from the Clipboard.

I provide further reasons why, when possible, you should try to avoid copying to the Clipboard near the beginning of this blog post when answering the question of whether, when working with the Range.Copy method, you should copy to the Clipboard or a Destination. Overall, there seems to be little controversy around the suggestion that (when possible) you should avoid the multi-step process of copying and pasting.

The next example uses the Worksheet.Paste method again, but for purposes of setting up links to the source data.

Macro Example #5: Copy And Paste Links

The following sample macro (Copy_Paste_Link) uses, once more, the Worksheet.Paste method that appears in the previous example. The purpose of using this method is, however, different.

More precisely, this sample macro #5 uses the Worksheet.Paste method for purposes of pasting links to the source data.

Example VBA code to copy and paste links

As with the other macro examples within this tutorial that use the Clipboard, you may want to use the Application.CutCopyMode property for purposes of cancelling Cut or Copy mode. To do this, add the statement “Application.CutCopyMode = False” at the end of the Sub procedure. I explain this particular topic below.

Let’s take a closer look at each of the lines of code to understand the structure of this macro, which differs from others we’ve previously seen in this Excel tutorial.

Line #1: Worksheets(“Sample Data”).Range(“B5:M107”).Copy

This statement, used in all of the previous sample macros and explained above, copies the range of cells B5 to M107 within the “Sample Data” worksheet to the Clipboard.

Line #2: Worksheets(“Example 4 – Paste”).Activate

This statement uses the Worksheet.Activate method. The main purpose of the Worksheet.Activate VBA method is to activate the relevant worksheet. As explained in the Microsoft Dev Center, it’s “the equivalent to clicking the sheet’s tab”.

The basic syntax of the Worksheet.Activate method is:

expression.Activate[/code]

“expression” is a variable representing a Worksheet object. In this particular macro example, “expression” is “Worksheets(“Example 5 – Paste Link”)”.

You can also activate a worksheet in a different workbook by qualifying the object reference, as I introduce above.

Line #3: ActiveSheet.Range(“B5”).Select

This particular statement uses the Range.Select VBA method. The purpose of this method is to select the relevant range.

The syntax of the Range.Select method is:

expression.Select

In this particular case, “expression” is a variable representing a Range object. In the example we’re looking at, this expression is “ActiveSheet.Range(“B5″)”.

The first item within this expression (“ActiveSheet”) is the Application.ActiveSheet property. This property returns the active sheet in the active workbook. The second item (“Range (“B5″)”) makes reference to cell B5.

As a consequence of the above, this statement selects cell B5 of the “Example 5 – Paste Link” worksheet. This worksheet was activated by the previous line of code.

Lines #4 And #5: ActiveSheet.Paste Link:=True

The use of the Worksheet.Activate method in line #2 and the Range.Select method in line #3 is an important difference between this macro sample #5 and the previous sample macros we’ve seen in this tutorial.

The reason why this particular Sub procedure (Copy_Paste_Link) uses the Worksheet.Activate and Range.Select method is that you can’t use the Destination parameter of the Paste method when using the Link parameter. In the absence of the Destination parameter, the Worksheet.Paste method pastes the contents of the Clipboard on the current selection. That current selection is (in this case) determined by the Worksheet.Activate and Range.Select methods as shown above.

In other words, since cell B5 of the “Example 5 – Paste Link” worksheet is the current selection, this is where the items within the Clipboard are pasted.

VBA code example to copy and paste with Activate and Select methods

This particular statement uses the Worksheet.Paste method alongside with its Link parameter for purposes of only pasting links to the data sources. This is done by setting the Link parameter to True.

Sample VBA code with Worksheet.Paste method

Line #5: Worksheets(“Example 5 – Paste Link”).Columns(“B:M”).AutoFit

This line isn’t absolutely necessary for purposes of copying and pasting links. I include it, mainly, for purposes of improving the readability of the destination worksheet (Example 5 – Paste Link).

Since this line repeats itself in other sample macros within this blog post, I explain it in more detail above. For purposes of this section, is enough to know that its purpose is to autofit the width of the destination columns (B through M) of the worksheet where the links are pasted (Example 5 – Paste Link).

The following image shows the results of executing the sample Copy_Paste_Link macro. Notice the effects this has in comparison with other methods used by previous sample macros. In particular, notice how (i) no borders or number formatting has been pasted, and (ii) cells that are blank in the source range result in a 0 being displayed when the link is established.

Excel table result of copying and pasting links with VBA

Excel VBA Copy Paste With The Range.CopyPicture Method

As anticipated above, the Range.CopyPicture VBA method allows you to copy a Range object as a picture.

The object is always copied to the Clipboard. In other words, there’s no Destination parameter that allows you to specify the destination of the copied range.

Range.CopyPicture Method: Syntax And Parameters

The basic syntax of the Range.CopyPicture method is the following:

expression.CopyPicture(Appearance, Format)

“expression” stands for the Range object you want to copy.

The CopyPicture method has 2 optional parameters: Appearance and Format. Notice that these 2 parameters are exactly the same as those that Excel displays in the Copy Picture dialog box.

Copy Picture regular dialog in Excel

This Copy Picture dialog box is displayed when you manually execute the Copy as Picture command.

The purpose and values that each of the parameters (Appearance and Format) can take within Visual Basic for Applications reflect the Copy Picture dialog box. Let’s take a look at what this means more precisely:

The Appearance parameter specifies how the copied range is actually copied as a picture. Within VBA, you specify this by using the appropriate value from the XlPictureAppearance enumeration. More precisely:

  • xlScreen (or 1) means that the appearance should resemble that displayed on screen as close as possible.
  • xlPrinter (or 2) means that the picture is copied as it is shown when printed.

The Format parameter allows you to specify the format of the picture. The enumeration you use to specify the formats is the XlCopyPictureFormat enumeration, which is as follows:

  • xlBitmap (or 2) stands for bitmap (.bmp, .jpg or .gif formats).
  • xlPicture (or -4147) represents drawn picture (.png, .wmf or .mix) formats.

Let’s take a look at an example which uses the Range.CopyPicture VBA method in practice:

Macro Example #6: Copy As Picture

The following Sub procedure (Copy_Picture) works with the same source data as all of the previous examples. However, in this particular case, the data is copied as a picture thanks to the Range.CopyPicture method.

Example VBA code to copy as picture

Let’s go through each of the lines of code separately to understand how the macro works:

Lines #1 To #3: Worksheets(“Sample Data”).Range(“B5:M107”).CopyPicture Appearance:=xlScreen, Format:=xlPicture

Lines #1 through #3 use the Range.CopyPicture VBA method for purposes of copying the relevant range of cells as a picture.

Notice how, this line of code is very similar to, but not the same as, the opening statements in all of the previous sample macros. The reason for this is that, this particular macro example #6 uses the Range.CopyPicture method instead of the Range.Copy method used by the previous macro samples.

Let’s break this statement in the following 4 items in order to understand better how it works and how it differs from the previous macro examples:

Example macro code to copy as picture

  • Item #1: “Worksheets(“Sample Data”).Range(“B5:M107″)”.
    • This item uses the Worksheet.Range property for purposes of returning the range object that is copied as a picture. More precisely, this Range object that is copied as a picture is made up of cells B5 to 107 within the “Sample Data” worksheet.
  • Item #2: “CopyPicture”.
    • This makes reference to the Range.CopyPicture method that we’re analyzing.
  • Item #3: “Appearance:=xlScreen”.
    • This item is the Appearance property of the Range.CopyPicture method. You can use this for purposes of specifying how the copied range is copied as a picture. In this particular case, Excel copies the range in such a way that it resembles how it’s displayed on the screen (as much as possible).
  • Item #4: “Format:=xlPicture”.
    • This is the Format property of the CopyPicture method. You can use this property to determine the format of the copied picture. In this particular example, the value of xlPicture represents drawn picture (.png, .wmf or .mix) formats.

Lines #5 And #6: Worksheets(“Example 6 – Copy Picture”).Paste Destination:=Worksheets(“Example 6 – Copy Picture”).Range(“B5”)

This statement uses the Worksheets.Paste method that I explain above for purposes of pasting the picture copied using the Range.CopyPicture method above. Notice how this statement is very similar to that which I use in macro example #4 above.

In order to understand in more detail how the statement works, let’s break it into the following 3 items:

Example of macro to copy as picture and paste

  • Item #1: “Worksheets(“Example 6 – Copy Picture”)”.
    • This item uses the Applications.Worksheets VBA property for purposes of returning the worksheet where the picture that’s been copied previously is pasted. In this particular case, that worksheet is “Example 6 – Copy Picture”.
    • If you want to paste the picture in a different workbook, you just need to appropriately qualify the object reference as I explain at the beginning of this Excel tutorial.
  • Item #2: “Paste”.
    • This makes reference to the Worksheet.Paste method.
  • Item #3: “Destination:=Worksheets(“Example 6 – Copy Picture”).Range(“B5″)”.
    • This is item sets the Destination parameter of the Worksheet.Paste method. This is the destination where the picture within the Clipboard is pasted. In this particular case, this is set by using the Worksheet.Range property to specify cell B5 of the worksheet “Example 6 – Copy Picture”.

The following screenshot shows the results obtained when executing the sample macro #6 (Copy_Picture). Notice how source data is indeed (now) a picture. Check out, for example, the handles that allow you to rotate and resize the image.

Example of results of macro that copies as picture

Excel VBA Copy Paste With The Range.Value And Range.Formula Properties

These methods don’t, strictly speaking, copy and paste the contents of a cell range. However, you may find them helpful if all you want to do is copy and paste the (i) values or (ii) the formulas of particular source range in another destination range.

In fact, if you’re only copying and pasting values or formulas, you probably should be using this way of carrying out the task with Visual Basic for Applications instead of relying on the Range.PasteSpecial method I introduce above. The main reason for this is performance and speed: This strategy tends to result in faster VBA code (than working with the Range.Copy method).

In order to achieve your purposes of copying and pasting values or formulas using this faster method, you’ll be using the Range.Value VBA property or the Range.Formula property (depending on the case).

  • The Range.Value property returns or sets the value of a particular range.
  • The Range.Formula property returns or sets the formula in A1-style notation.

The basic syntax of both properties is similar. In the case of the Range.Value property, this is:

expression.Value(RangeValueDataType)

For the Range.Formula property, the syntax is as follows:

expression.Formula

In both cases, “expression” is a variable representing a Range object.

The only optional parameter of the Range.Value property us RangeValueDataType, which specifies the range value data type by using the values within the xlRangeValueDataType enumeration. However, you can understand how to implement the method I describe here for purposes of copying and pasting values from one range to another without focusing too much on this parameter.

Let’s take a look at how you can use these 2 properties for purposes of copying and pasting values and formulas by checking out some practical examples:

Macro Example #7: Set Value Property Of Destination Range

The following macro (Change_Values) sets the values of cells B5 to M107 of the worksheet “Example 7 – Values” to be equal to the values of cells B5 to M107 of the worksheet “Sample Data”.

Sample macro to copy values

For this way of copying and pasting values to work, the size of the source and destination ranges must be the same. The macro example above complies with this condition. Alternatively, you may want to check out the adjustment at thespreadsheetguru.com (by following the link above), which helps you guarantee that the 2 ranges are the same size.

Let’s take a closer at the VBA code row-by-row look:

Line #1: Worksheets(“Example 7 – Values”).Range(“B5:M107”).Value = Worksheets(“Sample Data”).Range(“B5:M107”).Value

This statement sets the Value property of a certain range (cells B5 to M107 of the “Example 7 – Values” worksheet) to be equal to the Value property of another range (cells B5 to M107 of the “Sample Data” worksheet).

I explain how you can set and read object properties in detail in this Excel tutorial. In this particular case, this is done as follows:

Line #2: Worksheets(“Example 7 – Values”).Columns(“B:M”).AutoFit

This statement is used several times in previous macro examples. I explain it in more detail above.

Its main purpose is to autofit the width of the columns where the cells whose values are set by the macro (the destination cells) are located. In this particular example, those are columns B to M of the “Example 7 – Values” worksheet.

The following screenshot shows the results I get when executing the Change_Values macro.

Result of using macro to change values

The following example, which sets the Formula property of the destination range, is analogous to this one. Let’s take a look at it:

Macro Example #8: Set Formula Property Of Destination Range

As anticipated, the following macro (Change_Formulas) works in a very similar way to the previous example #7. The main difference is that, in this particular case, the purpose of the Sub procedure is to set formulas, instead of values. More precisely, the macro sets the formulas of cells B5 to M107 of the “Example 8 – Formulas” worksheet to be the same as those of cells B5 to M107 of the “Sample Data” worksheet.

Example alternative macro to copy and paste formulas

The basic structure of this macro is virtually identical to that of the Change_Values Sub procedure that appears in macro example #7 above. Just as in that case, the source and destination ranges must be of the same size.

Let’s take, anyway, a quick look at each of the lines of code to ensure that we understand every detail:

Line #1: Worksheets(“Example 8 – Formulas”).Range(“B5:M107”).Formula = Worksheets(“Sample Data”).Range(“B5:M107”).Formula

This statement sets the Formula property of cells B5 to M107 of the “Example 8 – Formulas” worksheet to be equal to the Formula property of cells B5 to M107 of the “Sample Data” worksheet.

The basic structure of the statement is exactly the same to that in the previous macro example #7, with the difference that (now) we’re using the Range.Formula property instead of the Range.Value property. More precisely:

Line #2: Worksheets(“Example 8 – Formulas”).Columns(“B:M”).AutoFit

The purpose of this statement is to autofit the width of the columns where the cells whose formulas have changed are located.

The following screenshot shows the results obtained when executing this macro:

Result of macro that copies and pastes by changing formulas

Notice the following interesting aspects of how the Range.Formula property works:

  • When the cell contains a constant, the Formula property returns a constant. This applies, for example, for (i) the columns that hold the number of units sold, and (ii) the unit prices of Items A, B, C, D and E.
    Excel table with constants set by Formula property
  • If a cell is empty, Range.Formula returns an empty string. In the example we’re looking at, this explains the result in the blank cells between the row specifying unit prices and the main table.
    Result of Excel macro setting formulas from empty cells
  • Finally, if a cell contains a formula, the Range.Formula property returns the formula as a string, and includes the equal sign (=) at the beginning. In the sample worksheet, this explains the results obtained in the cells containing total sales (per item and the grand total).
    Excel table result of macro setting formulas

How To Cancel Cut or Copy Mode and Remove the Moving Border

Several of the VBA methods and macro examples included in this Excel tutorial use the Clipboard.

If you must (or choose to) use the Clipboard when copying and pasting cells or cell ranges with Visual Basic for Applications, you may want to cancel Cut or Copy mode prior to the end of your macros. This removes the moving border around the copied cell range.

The following screenshot shows how this moving border looks like in the case of the “Sample Data” worksheet that includes the source cell range that I’ve used in all of the macro examples within this blog post. Notice the dotted moving outline around the copied cell range:

Example Excel table with dotted moving outline after macro

The VBA statement you need to cancel Cut or Copy mode and remove the moving outline (that appears above) is as follows:

Application.CutCopyMode = False

This statement simply sets the Application.CutCopyMode VBA property to False. Including this statement at the end of a macro has the following 2 consequences:

  • Effect #1: The Cut or Copy mode is cancelled.
  • Effect #2: The moving border is removed.

The following image shows the VBA code of macro example #4 above, with this additional final statement for purposes of cancelling Cut or Copy mode.

Example macro with CutCopyMode property

If I execute this new version of the Copy_Paste sample macro, Excel automatically removes the moving border around the copied cell range in the “Sample Data” worksheet. Notice how, in the following screenshot, the relevant range isn’t surrounded by the moving border:

Example Excel table with Clipboard cleared after macro

Excel VBA Copy Paste: Other VBA Methods You May Want To Explore

The focus of this Excel tutorial is in copying and pasting data in ranges of cells.

You may, however, be interested in learning or exploring about other VBA methods that you can use for pasting other objects or achieve different objectives. If that is the case, perhaps one or more of the methods that I list below may be helpful:

  • The Chart.CopyPicture method, which pastes the selected chart object as a picture.
  • The Chart.Copy method and the Charts.Copy method, whose purpose is to copy chart sheets to another location.
  • The Chart.Paste method, which pastes data into a particular chart.
  • The ChartArea.Copy VBA method, whose purpose is to copy the chart area of a chart to the Clipboard.
  • The ChartObject.Copy method and the ChartObjects.Copy method, which copy embedded charts to the Clipboard.
  • The ChartObject.CopyPicture method and the ChartObjects.CopyPicture VBA method, which you can use to copy embedded charts to the Clipboard as a picture.
  • The Floor.Paste VBA method, which pastes a picture that is within the Clipboard on the floor of a particular chart.
  • The Point.Copy method, which (when a point in a series in a chart has a picture fill), copies the relevant picture to the Clipboard.
  • The Point.Paste method, whose purpose is to paste a picture from the Clipboard as the marker of a particular point in a series in a chart.
  • The Range.CopyFromRecordset method, which copies the contents of a Data Access Object (DAO) or an ActiveX Data Object (ADO) Recordset object to a worksheet.
  • The Series.Copy method, whose purpose is to copy the picture fill of the marker on a series in a chart (if the series has a picture fill).
  • The Series.Paste method, which pastes a picture from the Clipboard as the marker on a particular series in a chart.
  • The SeriesCollection.Paste VBA method, whose purpose is to paste the data on the Clipboard into a chart series collection.
  • The Shape.CopyPicture method, which copies an object to the Clipboard as a picture.
  • The Sheets.Copy method, which copies a sheet to another location.
  • The Slicer.Copy VBA method, whose purpose is to copy a slicer to the Clipboard.
  • The Walls.Paste method, which pastes a picture from the Clipboard on the walls of a chart.
  • The Worksheet.Copy method, which you can use to copy a sheet to another location.
  • The Worksheet.PasteSpecial VBA method, which pastes the contents that are within the Clipboard on the worksheet using a specified format. This particular method is commonly used for purposes of pasting (i) data from other applications, or (ii) pasting data in a particular format.

This list doesn’t include absolutely all the VBA methods that copy and paste objects. It covers (mostly) the methods that apply to some of the main objects you’re likely to work with on a consistent basis, such as charts and worksheets.

Conclusion

By completing this Excel tutorial, you’ve covered the most important VBA methods that you can use for purposes of copying and pasting cells and cell ranges in Excel. More precisely, you’ve read about:

  • The Range.Copy method.
  • The Range.PasteSpecial method.
  • The Worksheet.Paste method.
  • The Range.CopyPicture method.
  • The Range.Value and Range.Formula properties, and how you can use them for purposes of copying values and formulas between cells and cell ranges.

You’ve also seen how to use the Application.CutCopyMode property for purposes of cancelling the Cut or Copy mode, if you decide to use it in your copy-pasting macros.

In addition to covering the basics of each method and property, you’ve seen 8 different examples of VBA code that can be easily adjusted to cover other situations you may encounter.

This Excel VBA Copy Paste Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples above. You can get immediate free access to this workbook by clicking the button below.

Get immediate free access to the Excel VBA Copy Paste workbook example

Also, remember that you can easily adjust the source and destination cells in any of those macros by adequately qualifying the object references or modifying the range references.

The knowledge and examples you’ve acquired enables you to immediately start creating your own macros for purposes of copying and pasting cells and cell ranges in Excel.

I’m aware that, in some situations, you’ll want to copy and paste other objects (not cell ranges) with VBA. For those purposes, you can refer to the list of similar VBA methods that I’ve not covered in this Excel VBA tutorial.

  • Remove From My Forums
  • Question

  • Hello,

    I request users to copy Columns A:AV in their entirety in «Workbook A».  I then created a command button for them to paste the data into a separate Excel workbook, «Workbook B», to help eliminate errors.  What I wish to do is once they copy Columns
    A:AV in Workbook A, that the first row from this selection not be pasted into «Workbook B» when they press the command button.

    In other words, I am asking for code that will capture the clipboard contents and remove the first row, prior to being pasted elsewhere.

    I know that the simple answer is to have users select the required cells for copying, but the objective is to automate so as to minimize errors.  I am also not terribly experienced in VBA.

    Thanks!

Answers

  •  When I click the source file, I receive the «Microsoft Excel has stopped working error» and the file crashes.

    I am running this on Excel 2002 SP3.

    And in response to your offer above, yes, I do require the pasting to commence at cell A2 of the destination file.

    I have edited the code in my previous post instead of re-posting all code here. Now tested in xl2002.

    The original code was tested in xl2010. The Filter setting was incorrect for xl2002. See code between the hash (##) lines.  However, my xl2002 did not crash; just did not display the required files.

    I have assumed that Workbook A is an xls file. If it is a csv then alter the filter accordingly and change xls to csv.

    See also code between the asterisk (***) lines. I have now coded to always start destination paste as cell A2. I have left the previous code in place and just commented out. I have also added a line to clear the worksheet from row 2 down in case you are
    simply pasting over the previous data. If pasting over the previous data and the new data does not have as many rows as old data then old data will remain in place below the new data.

    Hope it all works for you now but feel free to get back to me if any problems.


    Regards, OssieMac

    • Marked as answer by

      Wednesday, July 4, 2012 3:56 PM

  • There are 2 methods you can use.

    Method 1: (PastSpecial) Separate lines of code required for Copy and PastSpecial plus suppress the message re large amount of data on the clipboard.

    rngToCopy.Copy

    rngDestin.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
            SkipBlanks:=False, Transpose:=False

           
    ‘Following line is to suppress message re large amount of dat on clipboard
    Application.CutCopyMode = False

    Method 2:  Single line of code. It simply resizes the destination to the same size as the source and makes the destination equal to source values.

    rngDestin.Resize(rngToCopy.Rows.Count, rngToCopy.Columns.Count) = rngToCopy.Value

    I prefer Method 2 because it does not change workbooks and sheets to the destination and it does not leave the destination data selected (highlighted).


    Regards, OssieMac

    • Marked as answer by
      R.Shaw
      Friday, September 7, 2012 11:03 PM

Результат чтения текста из буфера обмена

Функции для работы с буфером обмена

(очистка буфера обмена, запись в буфер обмена, чтение из буфера обмена)

ВНИМАНИЕ: для работы функций требуется установка ссылки на библиотеку Microsoft Forms 2.0 Object Library:

Public Sub SetClipboard(Obj As Variant)
    Dim MyDataObj As New DataObject
    MyDataObj.SetText Format(Obj)
    MyDataObj.PutInClipboard
End Sub
 
Public Sub SetTextIntoClipboard(ByVal txt As String)
    Dim MyDataObj As New DataObject
    MyDataObj.SetText txt
    MyDataObj.PutInClipboard
End Sub
 
Public Function GetClipboard() As Variant
    GetClipboard = "": On Error Resume Next
    Dim MyDataObj As New DataObject
    MyDataObj.GetFromClipboard: GetClipboard = MyDataObj.GetText()
End Function
 
Public Sub ClearClipboard()
    Dim MyDataObj As New DataObject
    MyDataObj.SetText "": MyDataObj.PutInClipboard
End Sub

Аналогичная функция ClipboardText (чтение текста из буфера обмена), но не требующая подключения библиотеки:

Sub ПримерИспользования()
    txt = ClipboardText
    MsgBox txt, vbInformation, "Содержимое буфера обмена Windows"
End Sub
 
Function ClipboardText() ' чтение из буфера обмена
    With GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
        .GetFromClipboard
        ClipboardText = .GetText
    End With
End Function
 
Sub SetClipboardText(ByVal txt$) ' запись в буфер обмена
    With GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
        .SetText txt$
        .PutInClipboard
    End With
End Sub
  • 68130 просмотров

Не получается применить макрос? Не удаётся изменить код под свои нужды?

Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.

Summary[edit | edit source]

There are three main ways to pass text to and from the clipboard with VBA code.

  • The DataObject method:
    • This is perhaps the simplest implementation.
    • Its main restriction is that the contents of the clipboard will be lost when the launching application is closed; generally this is not a problem when running Excel modules, but should be borne in mind.
    • Some users elsewhere report bugs. See DataObject Bugs Forum for details of the bugs and one suggested fix. All of the procedures on this page are tested and work well in both Windows 7 and Windows 8.1 for Excel 2010. The DataObject method has recently been adopted for the VBA Indenter module, in this same series.
    • Other methods avoid these restrictions. In the unlikely event of problems with these procedures, either of the next two methods would suffice.
    • An example of the DataObject method is given in section two of this page.
  • User form control methods:
    • When user forms are to be displayed, then the copy and paste methods of the text box can be used. These methods work well and are well tested.
    • When no user form is to be displayed, a hidden form can be used. The form with a text box, is loaded but never displayed. Then, the invisible user form’s controls can still then be coded as normal. The text box must have its Multiline property set to true for most useful text transfers. It will be found best, in general,to set the form’s ShowModal property to False; this allows for convenient code tracing and avoids many other confusions.
    • An example of the hidden user form method is given in section four. Another example in section three, for a visible user form, shows how to track the active text box prior to copy.
  • API methods:
    • These methods make use of Windows libraries, and have copious declarations in their module headings. That said, they work well, and are described by Microsoft documentation as being the most suitable.
    • One example of API use is displayed in section five. See Send-Information-to-the-Clipboard for more details.

DataObject Method[edit | edit source]

  • These methods make used of a DataObject . They are by far the most adaptable, since any text that can be placed in a variable can then be placed onto the clipboard using the PutInClipboard method. Text can also be brought into a VBA string variable with the GetFromClipboard method. The procedures CopyToClip() and GetFromClip() in the example below first send text to the clipboard, then fetch it again, before displaying the text in a message box. Set a reference to Microsoft Forms 2 in the editor options for this; if you cannot find it just add a user form to your project and it will be added to the selections.
  • Reports of bugs in DataObject methods are reported elsewhere. These apply to Windows versions beyond Win 7, and are reported to involve an unusual persistence between the object and the clipboard. If difficulty is found with these methods then either the dummy userform method or the API methods could be tried.
Sub testCopyAndPaste()
    'demonstrates copy and paste of text to variables
    'loads clipboard with date-time text then
    'fetches it back for display
    'Only good for text and clipboard content lost
    'when application closes.
        
    Dim sStrOut As String, sStrIn As String
    
    'get the current date-time string
    sStrOut = Now
    
    'copy text to clipboard
    CopyToClip sStrOut

    'retrieve from clipboard
    sStrIn = GetFromClip
    
    'display recovered text
    MsgBox sStrIn

End Sub

Function CopyToClip(sIn As String) As Boolean
    'passes the parameter string to the clipboard
    'set reference to Microsoft Forms 2.0 Object Library.
    'If ref not listed, inserting user form will list it.
    'Clipboard cleared when launch application closes.
    
    Dim DataOut As DataObject
    
    Set DataOut = New DataObject
    
    'first pass textbox text to dataobject
    DataOut.SetText sIn
    
    'then pass dataobject text to clipboard
    DataOut.PutInClipboard
    
    'release object variable
    Set DataOut = Nothing
    
    CopyToClip = True
    
End Function

Function GetFromClip() As String
    'passes clipboard text to function name
    'If clipboard not text, an error results
    'set reference to Microsoft Forms 2.0 Object Library.
    'If ref not listed, inserting user form will list it.
    'Clipboard cleared when launch application closes.
    
    Dim DataIn As DataObject
    
    Set DataIn = New DataObject
    
    'clipboard text to dataobject
    DataIn.GetFromClipboard
    
    'dataobject text to function string
    GetFromClip = DataIn.GetText
    
    'release object variable
    Set DataIn = Nothing
    
End Function

Visible User Form Method[edit | edit source]

The code module below provides the VBA code for a form module, (shown here as UserForm1). In it there are command button click routines for textbox Copy and Paste. To use the copy procedure the user simply selects some text then presses the button on the user form. To paste the contents of the clipboard into a textbox, the user must first place the insertion point somewhere within a textbox before pressing the requisite button.

In order to clarify which textbox is active, there is a mouse-up event for each, where a number is loaded into a module-level variable whenever a mouse is used in the box. Although this code is made for three textboxes, it can easily be extended to any number.

The code assumes that there is a user form UserForm1, with TextBox1, TextBox2, TextBox3, CommandButton1 and CommandButton2 in it. In addition, note that there is a module level variable in the code. Since the VBA code is fairly generic it applies to most MS Office applications.

Option Explicit
Dim nActTxtBx As Integer

Private Sub CommandButton1_Click()
'this is the "Paste at Cursor" button
'pastes clipboard active textbox's insertion point
'ie; the textbox last clicked with mouse
            
    Dim oTxt1 As Control, oTxt2 As Control, oTxt3 As Control
    Dim oFrm As UserForm, oTxt As Control, s As Long
    
    Set oFrm = UserForm1
    Set oTxt1 = oFrm.TextBox1
    Set oTxt2 = oFrm.TextBox2
    Set oTxt3 = oFrm.TextBox3
    
    'get the textbox with the focus
    Select Case nActTxtBx
    Case 0
        MsgBox "Please place the insertion point."
        Exit Sub
    Case 1
        Set oTxt = oTxt1
    Case 2
        Set oTxt = oTxt2
    Case 3
        Set oTxt = oTxt3
    Case Else
        Exit Sub
    End Select
    
    s = oTxt.SelStart
    With oTxt
        .Paste
        .SetFocus
        .SelStart = s
    End With

    Set oFrm = Nothing: Set oTxt = Nothing
    Set oTxt1 = Nothing: Set oTxt2 = Nothing
    Set oTxt3 = Nothing
End Sub

Private Sub CommandButton2_Click()
'this is the "Copy Selected Text" button
'copies selected text from textbox to clipboard
'ie; the textbox last clicked with mouse

    Dim oTxt1 As Control, oTxt2 As Control, oTxt3 As Control
    Dim oFrm As UserForm, oTxt As Control
    
    Set oFrm = UserForm1
    Set oTxt1 = oFrm.TextBox1
    Set oTxt2 = oFrm.TextBox2
    Set oTxt3 = oFrm.TextBox3
    
    'get reference to active textbox
    Select Case nActTxtBx
    Case 0
        MsgBox "Please make a selection."
        Exit Sub
    Case 1
        Set oTxt = oTxt1
    Case 2
        Set oTxt = oTxt2
    Case 3
        Set oTxt = oTxt3
    Case Else
        Exit Sub
    End Select
    
    'check that a selection was made
    'MsgBox oTxt.SelLength
    If oTxt.SelLength = 0 Then
        MsgBox "No selection found."
        Exit Sub
    End If
    
    With oTxt
        .Copy
        .SetFocus
        .SelStart = 0
    End With

    Set oFrm = Nothing: Set oTxt = Nothing
    Set oTxt1 = Nothing: Set oTxt2 = Nothing
    Set oTxt3 = Nothing

End Sub

Private Sub TextBox1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
                                ByVal X As Single, ByVal Y As Single)
    'loads an integer to denote active textbox when mouse makes selection
    nActTxtBx = 1
End Sub

Private Sub TextBox2_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
                                ByVal X As Single, ByVal Y As Single)
    'loads an integer to denote active textbox when mouse makes selection
    nActTxtBx = 2
End Sub

Private Sub TextBox3_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
                                ByVal X As Single, ByVal Y As Single)
    'loads an integer to denote active textbox when mouse makes selection
    nActTxtBx = 3
End Sub

Hidden User Form Method[edit | edit source]

This code should be placed in a standard module. The project needs a user form called Temp, with a single TextBox1 set with MultiLine=true. TextBox contents are always text.

Option Explicit

Sub TestClipboardProcs()
'run this
    
    CopyToClipboard "The string" & vbCrLf & _
                    "to copy..."
    MsgBox GetClipboard2

End Sub

Function GetClipboard2() As String
'PASTES clipboard into function name as a text string
'project needs userform named Temp
'with TextBox1 in it set with property Multiline=true
    
    Dim oTxt1 As Control, oFrm As UserForm
    Dim s As Long
    
    'load the temporary form
    Load Temp
    
    Set oFrm = Temp
    Set oTxt1 = oFrm.TextBox1
        
    s = oTxt1.SelStart
    With oTxt1
        .Paste
        .SetFocus
        .SelStart = s
    End With
    
    GetClipboard2 = oTxt1.Value
        
    Set oTxt1 = Nothing
    Set oFrm = Nothing
    Unload Temp

End Function

Function CopyToClipboard(sStr As String) As Boolean
'COPIES parameter variable text string value to clipboard
'project needs userform named Temp
'with TextBox1 in it set with property Multiline=true
    
    Dim oTxt1 As Control, oFrm As UserForm
    
    If sStr = "" Then
        MsgBox "Clipboard cannot hold an empty string."
        Exit Function
    End If
        
    'load the temporary form
    Load Temp
    
    Set oFrm = Temp
    Set oTxt1 = oFrm.TextBox1
    
    oTxt1.Value = sStr
        
    'copy textbox value to clipboard
    With oTxt1
        .SelStart = 0 'set up the selection
        .SelLength = .TextLength
        .Copy
        .SetFocus
        .SelStart = 0
    End With
        
    Set oTxt1 = Nothing
    Set oFrm = Nothing
    Unload Temp

    CopyToClipboard = True

End Function

API Method[edit | edit source]

The code below was tested on an Office 2010 version of Excel, 32 bit system, and worked well. Since that time, with 64 bit 2019 Excel, the code will not work in its current state, but needs further changes to the declarations for 64 bit use.

The following VBA code makes use of API calls, and is recommended by Microsoft in their MS Access page Send-Information-to-the-Clipboard. Such methods should overcome the current bugs in the the DataObject methods for Windows 8 and 10. The code should be copied into a standard module in its entirety.

Option Explicit
'Declarations for functions SetClipboard() and GetClipboard()
''from https://docs.microsoft.com/en-us/office/vba/access/concepts/windows-api/send-information-to-the-clipboard
Private Declare Function OpenClipboard Lib "user32.dll" (ByVal hWnd As Long) As Long
Private Declare Function EmptyClipboard Lib "user32.dll" () As Long
Private Declare Function CloseClipboard Lib "user32.dll" () As Long
Private Declare Function IsClipboardFormatAvailable Lib "user32.dll" (ByVal wFormat As Long) As Long
Private Declare Function GetClipboardData Lib "user32.dll" (ByVal wFormat As Long) As Long
Private Declare Function SetClipboardData Lib "user32.dll" (ByVal wFormat As Long, ByVal hMem As Long) As Long
Private Declare Function GlobalAlloc Lib "kernel32.dll" (ByVal wFlags As Long, ByVal dwBytes As Long) As Long
Private Declare Function GlobalLock Lib "kernel32.dll" (ByVal hMem As Long) As Long
Private Declare Function GlobalUnlock Lib "kernel32.dll" (ByVal hMem As Long) As Long
Private Declare Function GlobalSize Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function lstrcpy Lib "kernel32.dll" Alias "lstrcpyW" (ByVal lpString1 As Long, ByVal lpString2 As Long) As Long

Sub TestCopyPasteAPI()
    'API methods for clipboard
    Dim sIn As String, sOut As String
    
    sIn = "Sausages"
    SetClipboard sIn
    sOut = GetClipboard
    MsgBox sOut

End Sub

Public Sub SetClipboard(sUniText As String)
    'sets the clipboard with parameter string
      
    Dim iStrPtr As Long, iLen As Long
    Dim iLock As Long
    Const GMEM_MOVEABLE As Long = &H2
    Const GMEM_ZEROINIT As Long = &H40
    Const CF_UNICODETEXT As Long = &HD
    
    OpenClipboard 0&
    EmptyClipboard
    iLen = LenB(sUniText) + 2&
    iStrPtr = GlobalAlloc(GMEM_MOVEABLE Or GMEM_ZEROINIT, iLen)
    iLock = GlobalLock(iStrPtr)
    lstrcpy iLock, StrPtr(sUniText)
    GlobalUnlock iStrPtr
    SetClipboardData CF_UNICODETEXT, iStrPtr
    CloseClipboard

End Sub

Public Function GetClipboard() As String
    'gets the clipboard text in function name
    
    Dim iStrPtr As Long, iLen As Long
    Dim iLock As Long, sUniText As String
    Const CF_UNICODETEXT As Long = 13&
    
    OpenClipboard 0&
    If IsClipboardFormatAvailable(CF_UNICODETEXT) Then
        iStrPtr = GetClipboardData(CF_UNICODETEXT)
        If iStrPtr Then
            iLock = GlobalLock(iStrPtr)
            iLen = GlobalSize(iStrPtr)
            sUniText = String$(iLen  2& - 1&, vbNullChar)
            lstrcpy StrPtr(sUniText), iLock
            GlobalUnlock iStrPtr
        End If
        GetClipboard = sUniText
    End If
    CloseClipboard

End Function

See Also[edit | edit source]

  • Send-Information-to-the-Clipboard: A clearly worded page by Microsoft showing how to use API methods for the clipboard. Although described for MS Access, it works in MS Excel just as well.
  • DataObject Bugs Forum: A description of a DataObject bug for Windows versions beyond Win7.

I need a macro that adds a specific text, plus the content of my clipboard, at the end of the subject of all messages I have selected. How do I get the content of the clipboard automatically, without first pasting it into an Input Box?

Although Outlook VBA doesn’t include a paste from clipboard function directly, you can use the MSForms dataobject to transfer the clipboard contents to a string which is then called from VBA. You could also use use the Word object model to copy the message body to the clipboard.

You can also use Word’s ‘Keep Source Formatting’ to paste formatted text into an Item Body. Code sample is at Paste formatted text using VBA

Add code similar to this to your macro:

 Dim DataObj As MSForms.DataObject
 Set DataObj = New MSForms.DataObject
 DataObj.GetFromClipboard

strPaste = DataObj.GetText(1)

The finished code will look something like the following. Note, you will need to have a reference to the Forms library in Tools, References.
Add the forms library as a reference
If you receive a «User-defined type not defined» you are missing the reference to Microsoft Forms 2.0 Object Library. If its not listed, add C:WindowsSystem32FM20.dll or C:WindowsFM20.dll as a reference.

Sub AddtoSubject()
 Dim ex As Explorer
 Dim mail As MailItem
 Set ex = Application.ActiveExplorer
 Dim strPaste  As Variant
 
Dim DataObj As MSForms.DataObject
Set DataObj = New MSForms.DataObject
DataObj.GetFromClipboard

strPaste = DataObj.GetText(1)

If strPaste = False Then Exit Sub
If strPaste = "" Then Exit Sub

 For Each mail In ex.Selection
    mail.Subject = mail.Subject & " my text " & strPaste
    mail.Save
 Next mail
 
Set DataObj  = Nothing
End Sub

Copy to Clipboard

What about going in the other direction: copying text to the clipboard? Use PutInClipboard to capture the text.

Remember, if you receive a «User-defined type not defined» you are missing the reference to Microsoft Forms 2.0 Object Library. If its not listed, add C:WindowsSystem32FM20.dll or C:WindowsFM20.dll as a reference.

Sub CapturetoClipbaord()
Dim oMail As MailItem
DataObj As MSForms.DataObject

    Set oMail = ActiveExplorer().Selection.Item(1)
    Set DataObj = New MSForms.DataObject
    DataObj.SetText oMail.Body
    DataObj.PutInClipboard
End Sub

Use Word Object Model to Copy (and Paste)

Current versions of Outlook use Word as the email as the email editor and can use the Word object model library to do things not normally supported in Outlook.

This sample copies the body of the selected message to the clipboard. To paste, use
objSel.PasteAndFormat (wdFormatOriginalFormatting)

Don’t forget to set a reference to Word’s Object model in Tools, References.

Sub CopyMessage()
    Dim objMail As Outlook.MailItem
    Dim objInsp As Inspector
    Dim objDoc As Word.Document
    Dim objSel As Word.Selection

Set objMail = Application.ActiveExplorer.Selection.Item(1)

  If Not objMail Is Nothing Then
        If objMail.Class = olMail Then

            Set objInsp = objMail.GetInspector
            If objInsp.EditorType = olEditorWord Then
                Set objDoc = objInsp.WordEditor
                Set objWord = objDoc.Application
                Set objSel = objWord.Selection
        With objSel
            .WholeStory
            .Copy
       End With
            End If
        End If
    End If
    
    Set objMail = Nothing
End Sub

This sample shows how to paste the copied content into a new message:

    Dim objMail As Outlook.MailItem
    Dim objInsp As Inspector
    Dim objDoc As Word.Document
    Dim objSel As Word.Selection

Set objMail = Application.CreateItem(olMailItem)
With objMail
  .To = "Alias@domain.com"
  .Subject = "This is the subject"
  .Display
End With

Set objInsp = objMail.GetInspector
If objInsp.EditorType = olEditorWord Then
    Set objDoc = objInsp.WordEditor
    Set objWord = objDoc.Application
    Set objSel = objWord.Selection
        
objSel.PasteAndFormat (wdFormatOriginalFormatting)
End If

Set objMail = Nothing
End Sub

Paste format types are below. For more information see WdRecoveryType Enumeration (Word).

Name Description
wdChart Pastes a Microsoft Office Excel chart as an embedded OLE object.
wdChartLinked Pastes an Excel chart and links it to the original Excel spreadsheet.
wdChartPicture Pastes an Excel chart as a picture.
wdFormatOriginalFormatting Preserves original formatting of the pasted material.
wdFormatPlainText Pastes as plain, unformatted text.
wdFormatSurroundingFormattingWithEmphasis Matches the formatting of the pasted text to the formatting of surrounding text.
wdListCombineWithExistingList Merges a pasted list with neighboring lists.
wdListContinueNumbering Continues numbering of a pasted list from the list in the document.
wdListDontMerge Not supported.
wdListRestartNumbering Restarts numbering of a pasted list.
wdPasteDefault Not supported.
wdSingleCellTable Pastes a single cell table as a separate table.
wdSingleCellText Pastes a single cell as text.
wdTableAppendTable Merges pasted cells into an existing table by inserting the pasted rows between the selected rows.
wdTableInsertAsRows Inserts a pasted table as rows between two rows in the target table.
wdTableOriginalFormatting Pastes an appended table without merging table styles.
wdTableOverwriteCells Pastes table cells and overwrites existing table cells.
wdUseDestinationStylesRecovery Uses the styles that are in use in the destination document.

To move image from one sheet to another through clipboard standard methods Copy-Paste are used. For Paste method you must define the range where the image is to be pasted, for example (you may skip Destination parameter):

Worksheets("Sheet1").Range("C1:C5").Copy
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("D1:D5")

A picture is inserted in the specified region, but some peculiarities exist:

  • for Office 2003 pasted image is not binded exactly to upper-left
    corner of the range; if you define an alone cell the image may get
    the position more left and lower, even may get the adjacent cell; so
    you must execute realign procedure using Top and Left properties
    (see below);
  • for Office 2003 pasted picture IS NOR selected, so special procedure
    must be done to identify the image in Shapes collection;

  • for Office 2007 image is selected and binded to upper-left corner of
    the specified range, so Selection property can be used to change the
    image property in the collection (Name for example);

  • pasted image index in Shapes collection becomes the upmost BUT AMONG
    THE PICTURES set (Type=msoPicture); in Office 2003 Shapes are
    groupped so that first is the block of controls (Lstbox, Combobox,
    etc.) and images block is latter, so pasted image index is in fact
    the last in all collection; for Office 2007 images block turns out to
    be BEFORE the block of controls, therefore you should search the
    index of the last pasted image between the elements of IMAGE BLOCK
    (see example below);

  • to deselect pasted image (not to delete it by accident) you should
    move focus to any cell/ for example as Range(«A1»).Select.

Hence, to write a universal program that works correctly either in Office 2003, or Office 2007 environment you should:

  • first, use special procedure to find out the pasted image (the reference, or index, of it in Shapes collection);
  • second, make image alignment to upper-left corner of the range where the image is pasted;
  • third, move focus to another cell.

Below is the Function that defines the index of last pasted image in the Shapes collection:

Function GetIndexPastedPicture() As Integer
' Pasted picture has the upmost index among the PICTURE block 
' But it is not necessarily the last inde[ in whole collection
' set reference to target sheet with pasted image
Set ThisDBSheet = Workbooks("BookName.xls").Worksheets("SheetName")
Dim sh As Shape, picIdx As Integer
picIdx = 0 ' initial value of index in Shapes collection, starts from 1
For Each sh In ThisDBSheet.Shapes
    If sh.Type = msoPicture Then ' image found
        picIdx = sh.ZOrderPosition ' image index
    End If
Next
' after For loop, picIdx - is the last index in PICTURE block 
GetIndexPastedPicture = picIdx
End Function

Then (assuming that Clipboard already has the proper image) the procedure to paste image looks like following:

Sub InsPicFromClipbrd(sInsCell As String, sPicName As String)
' Image is pasted to cell with name sInsCell,
' it is aligned to upper-left corner of the cell, 
' pasted image gets name sPicName in Shapes collection
' set reference to target sheet with pasted image
Set ThisDBSheet = Workbooks("BookName.xls").Worksheets("SheetName")
ThisDBSheet.Paste Destination:=Range(sInsCell) ' paste image fom clipboard
c1 = GetIndexPastedPicture() ' get index of pasted image (see above)
With ThisDBSheet.Shapes.Item(c1) ' correct the properties of the pasted image 
    .Top = Range(sInsCell).Top ' top alignment
    .Left = Range(sInsCell).Left ' left alignment
    .Name = sPicName ' assign new name
End With
Range("I18").Activate ' move focus from image
End Sub 'InsPicFromClipbrd

Понравилась статья? Поделить с друзьями:
  • Copy formula to all cells excel
  • Copy formula in cell excel
  • Copy formatting in word document
  • Copy format to word document
  • Copy format text in word