Копирование текста в макросе 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


In this Article

  • Copy (Cut) and Paste a Single Cell
  • VBA Coding Made Easy
  • Copy Selection
  • Copy (Cut) and Paste a Range of Cells
  • Copy (Cut) and Paste an Entire Column
  • Copy (Cut) and Paste an Entire Row
  • Copy (Cut) and Paste to Another Worksheet or Workbook
  • Value Paste
  • Paste Special
    • Clear Clipboard

In this tutorial, you will learn several different methods to Copy & Paste and Cut & Paste using a VBA macro. Read the companion tutorial on Value Pasting and PasteSpecial for more advanced copying and pasting options.

To use this code: Open the Visual Basic Editor (Alt + F11), Insert a new module (Insert > Module) and copy & paste the desired code into the module.

Copy (Cut) and Paste a Single Cell

This example copies or cuts and pastes a single cell, A1 over to B1:

Sub Paste_OneCell()

    'Copy and Paste Single Cell
    Range("A1").Copy Range("B1")

    'Cut and Paste Single Cell
    Range("A1").Cut Range("B1")

End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

Learn More!

Copy Selection

If you want to copy the active selection use this:

Sub CopySelection()

'Paste to a Defined Range
Selection.copy range("b1")

'Offset Paste (offsets 2 cells down and 1 to the right
Selection.copy
Selection.offset(2,1).Select
ActiveSheet.Paste

Application.CutCopyMode = False

End Sub

Copy (Cut) and Paste a Range of Cells

This example copies or cuts and pastes a range of cells, A1:A3 over to B1:B3 :

Sub Paste_Range()

    'Copy and Paste a Range of Cells
    Range("A1:A3").Copy Range("B1:B3")

    'Cut and Paste a Range of Cells
    Range("A1:A3").Cut Range("B1:B3")

End Sub

Copy (Cut) and Paste an Entire Column

Below we will demonstrate a couple of quick examples. Read our article on Copying and Pasting Rows and Columns for detailed examples, explanations, and variations.

This example copies or cuts and pastes an entire column, A over to B:

Sub PasteOneColumn()

    'Copy and Paste Column
    Range("A:A").Copy Range("B:B")


    'Cut and Paste Column
    Range("A:A").Cut Range("B:B")

End Sub

Copy (Cut) and Paste an Entire Row

This example copies or cuts and pastes an entire row, 1 over to 2:

Sub Paste_OneRow()

    'Copy and Paste Row
    Range("1:1").Copy Range("2:2")


    'Cut and Paste Row
    Range("1:1").Cut Range("2:2")

End Sub

Copy (Cut) and Paste to Another Worksheet or Workbook

Sub Paste_Other_Sheet_or_Book()

    'Cut or Copy and Paste to another worksheet
    Worksheets("sheet1").Range("A1").Copy Worksheets("sheet2").Range("B1") 'Copy
    Worksheets("sheet1").Range("A1").Cut Worksheets("sheet2").Range("B1") 'Cut

    'Cut or Copy and Paste to another workbook
    Workbooks("book1.xlsm").Worksheets("sheet1").Range("A1").Copy _ 
    Workbooks("book2.xlsm").Worksheets("sheet1").Range("B1") 'Copy
    Workbooks("book1.xlsm").Worksheets("sheet1").Range("A1").Cut _ 
    Workbooks("book2.xlsm").Worksheets("sheet1").Range("B1") 'Cut

    Application.CutCopyMode = False
End Sub

Value Paste

Normally, when you Copy and Paste you Paste all the properties of a cell: formatting, formulas, etc.. Value Pasting allows you to Copy and Paste cells’ values and nothing else. The easiest way to Value Paste in VBA is to define the cell’s value directly:

Sub ValuePaste()

    'Value Paste Cells
    Range("B1").value = Range("A1").value
    Range("B1:B3").value = Range("A1:A3").value

    'Set Values Between Worksheets
    Worksheets("sheet2").range("A1").value = Worksheets("sheet1").range("A1").value

    'Set Values Between Workbooks
    Workbooks("book2.xlsm").Worksheets("sheet1").range("A1").value = _
    Workbooks("book1.xlsm").Worksheets("sheet1").range("A1").value

    Application.CutCopyMode = False
End Sub

Paste Special

Paste Special allows you to Copy and Paste specific properties of cells (examples: formats, values, column widths, etc.). It also allows you to perform special paste operations (examples: skip blanks, transpose). We will look at several examples below, but for an in-depth read our tutorial on Value Pasting and Paste Special.

Sub PasteSpecial()

    'Perform one Paste Special Operation:
    Range("A1").Copy
    'Paste Formats
    Range("B1").PasteSpecial Paste:=xlPasteFormats
    'Paste Column Widths
    Range("B1").PasteSpecial Paste:=xlPasteColumnWidths
    'Paste Formulas
    Range("B1").PasteSpecial Paste:=xlPasteFormulas

    'Perform Multiple Paste Special Operations at Once:
    Range("A1").Copy
    'Paste Formats and Transpose
    Range("B1").PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=True

    Application.CutCopyMode = False
End Sub

Clear Clipboard

After Copying & Pasting you might want to clear the clipboard (we do in some of the code examples above).  To clear the Excel clipboard, we set Application.CutCopyMode to False:

Application.CutCopyMode = False

vba clear clipboard

This will clear Excel’s clipboard. However, it will not clear the Windows Clipboard. To clear the Window’s clipboard follow the instructions here.

 

zixoge111

Пользователь

Сообщений: 12
Регистрация: 13.04.2017

Как сделать макрос, который будет постоянно копировать одну ячейку, как текст, в другую?

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 14.09.2012

Контакты см. в профиле

Для начала записать саму процедуру копирования макрорекордером.

 

zixoge111

Пользователь

Сообщений: 12
Регистрация: 13.04.2017

 

Dyroff

Пользователь

Сообщений: 1133
Регистрация: 01.01.1970

#4

17.04.2017 11:47:06

zixoge111,

Код
Sub Макрос2()
    Range("B3").Select 'выделяем ячейку в которую хотим вставить
    Selection.NumberFormat = "@" 'устанавливаем текстовый формат ячейки 
    Range("A3").Select 'выделяем и копируем нужную ячеку
    Selection.Copy
    Range("B3").Select
    ActiveSheet.Paste 'вставляем в отформатированную  заранее ячейку 
End Sub

Изменено: Dyroff17.04.2017 11:48:22

Нужно бежать со всех ног, чтобы только оставаться на месте, а чтобы куда-то попасть, надо бежать как минимум вдвое быстрее!

 

zixoge111

Пользователь

Сообщений: 12
Регистрация: 13.04.2017

#5

17.04.2017 11:50:26

Цитата
Dyroff написал:
ActiveSheet.Paste ‘вставляем в отформатированную  заранее ячейку

Спасибо, а это копирование будет именно как вставка Текста? (чтобы формула не скопировалась)

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 14.09.2012

Контакты см. в профиле

#6

17.04.2017 11:50:28

Цитата
zixoge111 написал:
В виде кода пожалуйста)

Включите рекордер, выполните нужное копирование, остановите рекордер — получите код.

 

Dyroff

Пользователь

Сообщений: 1133
Регистрация: 01.01.1970

zixoge111,  Вам Юрий М — советует очень хороший и простой способ:) Этой займет у Вас не более одной минуты.
Откройте макрорекордер, нажмите запись, встаньте в нужную ячейку откуда хотите скопировать, скопируйте, встаньте в ячейку, в которую нужно перенести -специальная вставка- вставить как значения. Остановите запись. Откройте макрос- нажмите изменить и увидите код)

Нужно бежать со всех ног, чтобы только оставаться на месте, а чтобы куда-то попасть, надо бежать как минимум вдвое быстрее!

 

zixoge111

Пользователь

Сообщений: 12
Регистрация: 13.04.2017

А как этот макрос зациклить, чтобы он постоянно копировал?

Изменено: zixoge11117.04.2017 12:20:51

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 14.09.2012

Контакты см. в профиле

zixoge111, почитайте эту

статью

. Способ 2.

 

copper-top

Пользователь

Сообщений: 1051
Регистрация: 22.10.2016

#10

17.04.2017 12:33:04

zixoge111, затем посмотрите эту

тему

.

In excel, I am trying to copy text from one cell to another cell in another sheet. The source cell contains formatted text (bold,underlined,different colors). But when I copy the text using VBA to the other cell, the formatting is lost.

I know it is because excel is copying only the text value. Is there a way we can read the HTML text (rather than plain text) from a cell?

I have googled this and did not get any answers. I know that if we use copy and paste methods, we can copy the formatting.
E.g.

Range("F10").Select
Selection.Copy
Range("I10").Select
ActiveSheet.Paste

But I want to do it without a copy and paste since my destination is a merged cell and not identically sized as my source cell. Is there an option available in excel VBA to do this?

EDIT:
I was able to solve it with the following code.

Range("I11").Value = Range("I10").Value
For i = 1 To Range("I10").Characters.Count
    Range("I11").Characters(i, 1).Font.Bold = Range("I10").Characters(i, 1).Font.Bold
    Range("I11").Characters(i, 1).Font.Color = Range("I10").Characters(i, 1).Font.Color
    Range("I11").Characters(i, 1).Font.Italic = Range("I10").Characters(i, 1).Font.Italic
    Range("I11").Characters(i, 1).Font.Underline = Range("I10").Characters(i, 1).Font.Underline
    Range("I11").Characters(i, 1).Font.FontStyle = Range("I10").Characters(i, 1).Font.FontStyle
Next i

How to copy and paste data using a Macro in Excel. I’ll show you multiple ways to do this, including across worksheets and workbooks.

Sections:

Simple Copy/Paste

Copy Entire Range

Copy between Worksheets

Copy between Workbooks

Notes

Simple Copy/Paste

Range("A1").Copy Range("B1")

This copies cell A1 to cell B1.

Range(«A1»).Copy is the part that copies the cell.

Range(«B1») is the cell where the data will be copied.

This is a simple one line piece of code and it’s very easy to use.

Notice that there is a space between these two parts of the code.

Copy Entire Range

Range("A1:A5").Copy Range("B1:B5")

Range(«A1:A5»).Copy is the part that copies the range.

Range(«B1:B5») is the range where the data will be copied.

You can also write it like this:

Range("A1:A5").Copy Range("B1")

Notice that the range to where you will copy the data has only a reference to cell B1.

You only have to reference the very first cell to which the range will be copied and the entire range will copy in the cells below there.

NOTE: if you do it like this, you may end up overwriting data and Excel will not give you a warning about this; the data will simply be filled down as far as it needs to go to copy the first range.

Copy between Worksheets

Sheets("Sheet1").Range("A1").Copy Sheets("Sheet2").Range("B1")

This follows the same pattern as the above examples except that we need to tell the macro from which sheet we want to get the data and to which sheet we want to copy the data.

Sheets(«Sheet1»). is placed in front of the first range and that means to get the data from Sheet1, which is the name of a worksheet in the workbook.

Sheets(«Sheet2»). is placed in front of the range to which we want to copy the data and Sheet2 is the name of the worksheet where the data will be copied.

Copy between Workbooks

Workbooks("Copy and Paste Data using Macro VBA in Excel.xlsm").Sheets("Sheet1").Range("A1").Copy Workbooks("Copy and Paste Data using Macro VBA in Excel.xlsm").Sheets("Sheet3").Range("A1")

Here, we follow the above examples and, this time, add a reference to the workbooks from which we want to get the data and to which we want to place the data.

Workbooks(«Copy and Paste Data using Macro VBA in Excel.xlsm»). is the code that says in which workbook we want to place the data. Copy and Paste Data using Macro VBA in Excel.xlsm is the name of the workbook. In this example I used this for both parts, the workbook from which the data comes and where it goes. This allows you to run this macro within a single workbook and still show you how it works. In a real-world example, the first part contains the name of the workbook where you get the data from and the second contains the name of the workbook where you want to place the data.

Read this tutorial to copy values from another workbook, even if it’s closed.

Notes

All examples in the attached workbook have been commented out. Simply remove the single quote from the line of code you want to test and then run the macro.

cf5e0ebf6d62c9ec73df03c55f727e77.jpg

Download the attached file to get these examples in Excel.

Similar Content on TeachExcel

Activate or Navigate to a Worksheet using Macros VBA in Excel

Tutorial: Make a particular worksheet visible using a macro in Excel.
This is called activating a wo…

Get the Name of a Worksheet in Macros VBA in Excel

Tutorial: How to get the name of a worksheet in Excel using VBA and Macros and also how to store tha…

Get the Last Row using VBA in Excel

Tutorial:
(file used in the video above)
How to find the last row of data using a Macro/VBA in Exce…

Remove Dashed Lines from Copy Paste VBA in Excel

Tutorial: How to remove the flashing dashes from a copy/paste range using VBA in Excel; this removes…

Copy one range and paste in another range

Tutorial: Below is a macro, just copy and paste it into a module in your workbook and go from there…

Guide to Combine and Consolidate Data in Excel

Tutorial: Guide to combining and consolidating data in Excel. This includes consolidating data from …

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Копирование текста в word с сохранением
  • Копирование текста в word с помощью клавиш
  • Копирование таблицы в excel с сохранением форматирования
  • Копирование таблицы в excel с сохранением размеров
  • Копирование таблицы excel 2003 в excel

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии