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
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
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
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
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
gtwebbgtwebb
2,9713 gold badges13 silver badges22 bronze badges
r.Copy
dest.pastespecial xlPastevalues
answered Jun 18, 2014 at 21:19
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.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.
answered Jan 30, 2018 at 4:08
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
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 Метки нет (Все метки)
Добрый день. Пишу макрос и на данный момент столкнулся со следующей проблемой: есть готовый код,с помощью которого я собираю информацию со всех листов на отдельном листе и не знаю что следует поправить в строке, чтобы вставлялись только значения. Выдержка из кода:
Что надо изменить в этой строке, чтобы вставлялись только значения? |
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:
Вариант № 2:
Примечание С большими диапазонами ячеек быстрее работает 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 |
|||
1 |
2 / 2 / 0 Регистрация: 15.10.2019 Сообщений: 46 |
|
16.10.2019, 09:20 |
5 |
не работает… пишет ошибку expected end of statement
0 |
Копирование только значений, без формул |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
Как копировать только значения ячеек?
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 руб./за проект