Копирование только значений vba 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

What This VBA Macro Code Does

The following two examples of VBA code show you how you can automate copy and pasting values only with an Excel range.

Using The Copy/PasteSpecial Method

This is the VBA code version of how you would manually paste values only in Excel with your mouse and keyboard. The code is simply copying a range and pasting the values only in a destination range. I like throwing in a line of code that clears out the clipboard so the marching ants are not still walking around your range after the macro code has run (just a personal preference).

This method probably makes the most sense to beginners as it mimics the manual steps you are accustomed to doing, however, it is not the most efficient way!

See the next method to optimize your code even more.

Using The Transfer Method

This method forgoes using the Copy/Paste clipboard altogether. What is the benefit of this you might be asking yourself?  One word…SPEED!

If you are needing to «paste values only» on a large amount of data or numerous iterations in a row, you definitely should use this method over the PasteSpecial method.

The only tricky part is making sure the two ranges you are «transferring» between are exactly the same size. By using the code I show below, you shouldn’t have a problem with this at all since the two ranges are guaranteed to be the same size.

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris
Founder, TheSpreadsheetGuru.com

Pekin

1

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

11.02.2013, 12:00. Показов 32790. Ответов 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



Копирование только значений, без формул

julia5555

Дата: Среда, 21.03.2018, 09:15 |
Сообщение № 1

Группа: Пользователи

Ранг: Новичок

Сообщений: 16


Репутация:

0

±

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


Excel 2013

Здравствуйте! не получается оптимизировать макрос чтобы копировал только значения
Сначала я копирую определенный лист из другой книги

[vba]

Код

Sub CombineWorkbooks()
Dim filestoopen
Dim x As Integer
Application.ScreenUpdating = False
filestoopen = Application.GetOpenFilename(filefilter:=»All files(*.*),*.*», MultiSelect:=True, Title:=»Files to Merge»)
If TypeName(filestoopen) = «Boolean» Then
MsgBox «Файл не выбран»
Exit Sub
End If

x = 1
While x <= UBound(filestoopen)
Set importWB = Workbooks.Open(Filename:=filestoopen(x))
Sheets(«Свод»).Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
importWB.Close savechanges:=False
x = x + 1
Wend
Application.ScreenUpdating = True

End Sub

[/vba]

Затем я на новом листе собираю свод из текущих листов, все копируется но с формулами

[vba]

Код

Sub www()
    Dim ws As Worksheet, l&
    With Sheets(«Svod»)
        .UsedRange.Offset(9).ClearContents
        For Each ws In Worksheets
            If Not ws.Name = «Svod» Then
                     l = .Cells.Find(«*», [a20], xlValues, 1, 1, 2).Row + 1
                ws.UsedRange.Offset(9).Copy .Range(«a» & l)
                        End If
        Next
    End With
End Sub

[/vba]

Как в свод скопировать только значения?
Спасибо

 

Ответить

Roman777

Дата: Среда, 21.03.2018, 09:53 |
Сообщение № 2

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

Ранг: Ветеран

Сообщений: 980


Репутация:

127

±

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


Excel 2007, Excel 2013

Используйте [vba][/vba] :msdn


Много чего не знаю!!!!

Сообщение отредактировал Roman777Среда, 21.03.2018, 09:54

 

Ответить

julia5555

Дата: Среда, 21.03.2018, 11:50 |
Сообщение № 3

Группа: Пользователи

Ранг: Новичок

Сообщений: 16


Репутация:

0

±

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


Excel 2013

Используйте
.PasteSpecial
:msdn

да да я знаю, но не получается, не могу верно прописать строку, сразу в ошибку

 

Ответить

Mikael

Дата: Среда, 21.03.2018, 12:32 |
Сообщение № 4

Группа: Пользователи

Ранг: Участник

Сообщений: 80


Репутация:

31

±

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


Excel 2010

julia5555, добрый день!
А так пробовали?
[vba]

Код

Sub www()
    Dim ws As Worksheet, l&
    With Sheets(«Svod»)
        .UsedRange.Offset(9).ClearContents
        For Each ws In Worksheets
            If Not ws.Name = «Svod» Then
                l = .Cells.Find(«*», [a20], xlValues, 1, 1, 2).Row + 1
                ws.UsedRange.Offset(9).Copy
                .Range(«a» & l).PasteSpecial xlPasteValues
                Application.CutCopyMode = 0
            End If
        Next
    End With
End Sub

[/vba]

 

Ответить

julia5555

Дата: Среда, 21.03.2018, 13:17 |
Сообщение № 5

Группа: Пользователи

Ранг: Новичок

Сообщений: 16


Репутация:

0

±

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


Excel 2013

julia5555, добрый день!А так пробовали?

не выходит, прикрепляю файл
[moder]Не нужно цитировать весь пост целиком — это нарушение правил.[/moder]

К сообщению приложен файл:

4688776.xlsm
(75.1 Kb)

 

Ответить

Mikael

Дата: Среда, 21.03.2018, 13:26 |
Сообщение № 6

Группа: Пользователи

Ранг: Участник

Сообщений: 80


Репутация:

31

±

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


Excel 2010

julia5555,
Попробуйте так:
[vba]

Код

Sub www_Mika()
    Dim ws As Worksheet, l&, aTmp
    With Sheets(«Svod»)
        .UsedRange.Offset(9).ClearContents
        For Each ws In Worksheets
            If Not ws.Name = «Svod» Then
                l = .Cells.Find(«*», [a20], xlValues, 1, 1, 2).Row + 1
                aTmp = ws.UsedRange.Offset(9).Value
                .Range(«a» & l).Resize(UBound(aTmp), UBound(aTmp, 2)).Value = aTmp
            End If
        Next
    End With
End Sub

[/vba]

UPD:
В Вашем файле проблема в 13 строке (17 на листе Svod) — уберите объединение ячеек

К сообщению приложен файл:

1416920.xlsm
(73.9 Kb)

Сообщение отредактировал MikaelСреда, 21.03.2018, 13:40

 

Ответить

julia5555

Дата: Среда, 21.03.2018, 14:13 |
Сообщение № 7

Группа: Пользователи

Ранг: Новичок

Сообщений: 16


Репутация:

0

±

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


Excel 2013

julia5555,Попробуйте так:

дааа, спасибо большое!
Не очень поняла почему мы пользовались[vba]

Код

.Range(«a» & l).Resize(UBound(aTmp), UBound(aTmp, 2)).Value = aTmp

[/vba] а не [vba]

Код

Range(«a» & l).PasteSpecial xlPasteValues

[/vba] щас буду читать, так как новичек в этой теме
Спасибо еще раз

 

Ответить

Mikael

Дата: Среда, 21.03.2018, 14:33 |
Сообщение № 8

Группа: Пользователи

Ранг: Участник

Сообщений: 80


Репутация:

31

±

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


Excel 2010

Не очень поняла почему мы пользовались

это решение через массив, я загружаю все данные с листа ws сначала в массив, а потом выгружаю этот массив на лист Svod. Этот метод куда быстрее копирования-вставки.

Чтобы использовать .PasteSpecial:

В Вашем файле проблема в 13 строке (17 на листе Svod) — уберите объединение ячеек

 

Ответить

julia5555

Дата: Среда, 28.03.2018, 06:54 |
Сообщение № 9

Группа: Пользователи

Ранг: Новичок

Сообщений: 16


Репутация:

0

±

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


Excel 2013

Спасибо большое, разобралась и все работает

 

Ответить

  • honor8

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

Sub m()
    For i = 1 To Sheets.Count
        If Sheets(i).Name <> "Общий" Then
           myR_Total = Sheets("Общий").Range("A" & Sheets("Общий").Rows.Count).End(xlUp).Row
           myR_i = Sheets(i).Range("A" & Sheets(i).Rows.Count).End(xlUp).Row

           If i = 1 Then
            Sheets(i).Rows("1:" & myR_i).Copy Sheets("Общий").Range("A" & myR_Total)
           Else
            Sheets(i).Rows("2:" & myR_i).Copy Sheets("Общий").Range("A" & myR_Total)
           End If

        End If
    Next
End Sub

Помогите пожалуйста откорректировать код макроса.
Он работает, только копирует в лист «Общий» формулы из всех других листов.
А мне нужны значения.


  • Вопрос задан

    более трёх лет назад

  • 252 просмотра

Ответ дали здесь

Sub m()
Set Sh = Worksheets("Общий")
For i = 1 To Sheets.Count
    myR_Total = Sh.Range("A" & Sh.Rows.Count).End(xlUp).Row
    With Sheets(i)
        If .Name <> "Общий" Then
            myR_i = .Range("A" & .Rows.Count).End(xlUp).Row
            j = IIf(i = 1, 1, 2)
            .Rows(j & ":" & myR_i).Copy
            Sh.Range("A" & myR_Total).PasteSpecial Paste:=xlPasteValues
        End If
    End With
Next
End Sub

Пригласить эксперта


  • Показать ещё
    Загружается…

16 апр. 2023, в 09:40

10000 руб./за проект

16 апр. 2023, в 08:25

20000 руб./за проект

16 апр. 2023, в 06:36

1000 руб./за проект

Минуточку внимания

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

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

  • Копирование только заливки excel
  • Копирование стилей документа word
  • Копирование только видимых ячеек excel
  • Копирование ссылок в несколько ячеек в excel
  • Копирование текстовых ячеек excel

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

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