Excel макрос скопировать только значения

I’m trying to copy values from a table to a Range, in Excel using vba Macros, but I dont want the table format, only its values. How can I achieve this?

Here is part of the code:

    'Source range
    Set r = Sheets("Sheet1").Range("Table1")

    'Destination range
    Set dest = Range(.Cells(linhaAtual, 1), .Cells(linhaAtual + r.Rows.Count - 1, 5))

    r.Copy Destination:= dest

asked Jun 18, 2014 at 20:59

pablo.vix's user avatar

You can skip the copy command altogether by assigning the values of the source range to your destination range:

'Source range
Set r = Sheets("Sheet1").Range("Table1")
'Destination range
Set dest = Range(.Cells(linhaAtual, 1), .Cells(linhaAtual + r.Rows.Count - 1, 5))

dest.Value = r.Value

answered Jun 19, 2014 at 12:47

MP24's user avatar

MP24MP24

3,07721 silver badges23 bronze badges

1

I believe you are looking for the functionality of pasting values. You can record it, or use what I have done below. (from recording so selecting is in there, which will make it run slower, but you aren’t looping so it is only constant time being added).

Selection.Copy
        'Select your destination like range("destination").select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False

answered Jun 18, 2014 at 21:11

Kory's user avatar

KoryKory

3081 silver badge7 bronze badges

1

I assume you want to copy from «Sheet1» to «Sheet1» — of course you can make this a parameter and loop through all your sheets

Dim rSource as range 'Source Range
Dim rDest as range   'Target Range - It should be the same dimension
Dim wbSource as workbook 'Source Workbook
Dim wbTarget as workbook 'Target Workbook
Dim myRange as string

myRange = "A:G" ' It is an example, you can make it dynamic

'add new workbook
    Workbooks.Add
    Set wbTarget = ActiveWorkbook

'Set the Source Range
    Set rSource = wbSource.Sheets("Sheet1").Range(myRange)

'Destination Range
    Set rDest = wbTarget.Sheets("Sheet1").Range(myRange)

'Copy values only
    rSource.Copy
    rDest.PasteSpecial xlPasteValues

answered Oct 8, 2018 at 17:20

pbou's user avatar

pboupbou

2782 silver badges13 bronze badges

You need to use the pastespecial command as shown below.

'Source range
Set r = Sheets("Sheet1").Range("Table1")

'Destination range
Set dest = Range(.Cells(linhaAtual, 1), .Cells(linhaAtual + r.Rows.Count - 1, 5))

r.Copy 
dest.pastespecial paste:=xlPasteValues

answered Jun 18, 2014 at 21:15

gtwebb's user avatar

gtwebbgtwebb

2,9713 gold badges13 silver badges22 bronze badges

r.Copy
dest.pastespecial xlPastevalues

answered Jun 18, 2014 at 21:19

user2649602's user avatar

1

I achieve a solution that works.

There follows the code:

    Set r = Sheets("Criteria").Range("CriteriaTable")

    Set dest = Range(.Cells(linhaAtual, 1), .Cells(linhaAtual + r.Rows.Count - 1, 5))
    Sheets("Criteria").Activate
    r.Select
    Selection.Copy
    Sheets("Load").Activate
    dest.Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

answered Jun 20, 2014 at 15:28

pablo.vix's user avatar

pablo.vixpablo.vix

2,0432 gold badges15 silver badges12 bronze badges

Use the Range.Value method. Its like setting a variable a = 1. Where you think of it as copying 1 to a. So…

Range2.value = Range1.value

or

Worksheets("historical").Range("A1:F15").Value =  Worksheets("actuals").Range("A1:F15").Value

Here I’m copying some data in worksheet actual to some historical worksheet. Or if you prefer setting the value of one range to another range.

Saurabh Bhandari's user avatar

answered Jan 30, 2018 at 4:08

RHH1095's user avatar

RHH1095RHH1095

791 silver badge4 bronze badges

You can skip the copy command altogether as MP24 said .. his suggestion worked for me after modifyibg the last line from «value» to «formula» as follows

Set r = Sheets(«Sheet1»).Range(«Table1»)
Set dest = Range(.Cells(linhaAtual, 1), .Cells(linhaAtual +
r.Rows.Count — 1, 5))

dest.formula = r.formula

answered Aug 1, 2022 at 6:42

Jawali M's user avatar

Pekin

1

Копировать только значения

11.02.2013, 12:00. Показов 32718. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Добрый день.

Пишу макрос и на данный момент столкнулся со следующей проблемой: есть готовый код,с помощью которого я собираю информацию со всех листов на отдельном листе и не знаю что следует поправить в строке, чтобы вставлялись только значения. Выдержка из кода:

PureBasic
1
Sheets("Sheets"1).Range(sCopyAddress).Copy wsDataSheet.Cells(lLastRowMyBook, 1).Offset(, lCol)

Что надо изменить в этой строке, чтобы вставлялись только значения?

Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

11.02.2013, 12:00

4

Скрипт

5468 / 1148 / 50

Регистрация: 15.09.2012

Сообщений: 3,514

11.02.2013, 12:14

2

Вариант № 1:

Visual Basic
1
2
3
4
5
6
Sub Procedure_1()
 
    Range("A1").Copy
    Range("B1").PasteSpecial Paste:=xlPasteValues
 
End Sub

Вариант № 2:

Visual Basic
1
2
3
4
5
Sub Procedure_2()
 
    Range("B1").Value = Range("A1").Value
 
End Sub

Примечание

С большими диапазонами ячеек быстрее работает PasteSpecial, чем второй вариант.



1



Pekin

11.02.2013, 12:26

3

@Скрипт

Спасибо за предлагаемые решения.

Моя проблема в том, что мне необходимо минимально изменить приведенный код, поскольку весь код громоздкий и используется множество команд (в приведенном коде, например, используется Offset) и вероятность проблем с новым кодом высока

Хотел бы увидеть предложение к конкретному коду (именно по нему не могу найти как выполнить данную задачу)

Watcher_1

356 / 162 / 27

Регистрация: 21.06.2011

Сообщений: 350

11.02.2013, 12:40

4

Visual Basic
1
2
Sheets("Sheets1").Range(sCopyAddress).Copy
wsDataSheet.Cells(lLastRowMyBook, 1).Offset(, lCol).PasteSpecial Paste:=xlPasteValues



1



2 / 2 / 0

Регистрация: 15.10.2019

Сообщений: 46

16.10.2019, 09:20

5

не работает…

пишет ошибку expected end of statement



0



Вырезание, перемещение, копирование и вставка ячеек (диапазонов) в VBA Excel. Методы Cut, Copy и PasteSpecial объекта Range, метод Paste объекта Worksheet.

Метод Range.Cut

Range.Cut – это метод, который вырезает объект Range (диапазон ячеек) в буфер обмена или перемещает его в указанное место на рабочем листе.

Синтаксис

Параметры

Параметры Описание
Destination Необязательный параметр. Диапазон ячеек рабочего листа, в который будет вставлен (перемещен) вырезанный объект Range (достаточно указать верхнюю левую ячейку диапазона). Если этот параметр опущен, объект вырезается в буфер обмена.

Для вставки на рабочий лист диапазона ячеек, вырезанного в буфер обмена методом Range.Cut, следует использовать метод Worksheet.Paste.

Метод Range.Copy

Range.Copy – это метод, который копирует объект Range (диапазон ячеек) в буфер обмена или в указанное место на рабочем листе.

Синтаксис

Параметры

Параметры Описание
Destination Необязательный параметр. Диапазон ячеек рабочего листа, в который будет вставлен скопированный объект Range (достаточно указать верхнюю левую ячейку диапазона). Если этот параметр опущен, объект копируется в буфер обмена.

Метод Worksheet.Paste

Worksheet.Paste – это метод, который вставляет содержимое буфера обмена на рабочий лист.

Синтаксис

Worksheet.Paste (Destination, Link)

Метод Worksheet.Paste работает как с диапазонами ячеек, вырезанными в буфер обмена методом Range.Cut, так и скопированными в буфер обмена методом Range.Copy.

Параметры

Параметры Описание
Destination Необязательный параметр. Диапазон (ячейка), указывающий место вставки содержимого буфера обмена. Если этот параметр не указан, используется текущий выделенный объект.
Link Необязательный параметр. Булево значение, которое указывает, устанавливать ли ссылку на источник вставленных данных: True – устанавливать, False – не устанавливать (значение по умолчанию).

В выражении с методом Worksheet.Paste можно указать только один из параметров: или Destination, или Link.

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

Примеры

Вырезание и вставка диапазона одной строкой (перемещение):

Range(«A1:C3»).Cut Range(«E1»)

Вырезание ячеек в буфер обмена и вставка методом ActiveSheet.Paste:

Range(«A1:C3»).Cut

ActiveSheet.Paste Range(«E1»)

Копирование и вставка диапазона одной строкой:

Range(«A18:C20»).Copy Range(«E18»)

Копирование ячеек в буфер обмена и вставка методом ActiveSheet.Paste:

Range(«A18:C20»).Copy

ActiveSheet.Paste Range(«E18»)

Копирование одной ячейки и вставка ее данных во все ячейки заданного диапазона:

Range(«A1»).Copy Range(«B1:D10»)


Макрос, копирование только значения.

Chelovekov

Дата: Вторник, 09.04.2019, 04:06 |
Сообщение № 1

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 235


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Здравствуйте, Уважаемые форумчане. помогите решить следующую проблему, есть написанный макрос, который копирует определенные ячейки и вставляет в другую таблицу. Нужно изменить его так , что бы он копировал только значения ячеек, без формул.

Код

Sub Отправить()

    Dim shSrc As Worksheet, shRes As Worksheet
    Dim lr As Long

        Application.ScreenUpdating = False

        Set shSrc = ThisWorkbook.Worksheets(«Данные»)
    Set shRes = ThisWorkbook.Worksheets(«Результаты»)

        lr = shRes.Cells(shRes.Rows.Count, «A»).End(xlUp).Row + 1
    shSrc.Range(«A2:I2»).Copy shRes.Cells(lr, «A»)

        shRes.Activate
    shSrc.Activate

        MsgBox «Готово!», vbInformation
    Application.ScreenUpdating = True

End Sub

 

Ответить

skais

Дата: Вторник, 09.04.2019, 08:43 |
Сообщение № 2

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 231


Репутация:

29

±

Замечаний:
20% ±


Excel 2010

[vba]

Код

shSrc.Range(«A2:I2»).Copy
shRes.Cells(lr, «A»).PasteSpecial (xlPasteValues)

[/vba]

 

Ответить

Chelovekov

Дата: Вторник, 09.04.2019, 10:27 |
Сообщение № 3

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 235


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Огромное спасибо hands

 

Ответить

_Boroda_

Дата: Вторник, 09.04.2019, 10:32 |
Сообщение № 4

Группа: Модераторы

Ранг: Местный житель

Сообщений: 16618


Репутация:

6465

±

Замечаний:
0% ±


2003; 2007; 2010; 2013 RUS

Какой красивый код. Цветной весь такой! (для тех, кто теги себе нормальные сделал http://www.excelworld.ru/forum/12-41046-273078-16-1552858824 ) Иван, ничего не хотите там поправить?
Подсказка — код VBA это кнопка #, а не fx

[vba]

Код

shRes.Cells(lr, «A»).Resize(, 9)=shSrc.Range(«A2:I2»).value

[/vba]

* Зачем Вам Activate там?


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

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!

Понравилась статья? Поделить с друзьями:
  • Excel макрос скопировать значение ячейки
  • Excel макрос скопировать диапазон ячеек
  • Excel макрос сколько строк
  • Excel макрос сбор данных с разных листов
  • Excel макрос с чего начать