Копирование формул без сдвига ссылок
Проблема
Предположим, что у нас есть вот такая несложная таблица, в которой подсчитываются суммы по каждому месяцу в двух городах, а затем итог переводится в евро по курсу из желтой ячейки J2.
Проблема в том, что если скопировать диапазон D2:D8 с формулами куда-нибудь в другое место на лист, то Microsoft Excel автоматически скорректирует ссылки в этих формулах, сдвинув их на новое место и перестав считать:
Задача: скопировать диапазон с формулами так, чтобы формулы не изменились и остались теми же самыми, сохранив результаты расчета.
Способ 1. Абсолютные ссылки
Как можно заметить по предыдущей картинке, Excel сдвигает только относительные ссылки. Абсолютная (со знаками $) ссылка на желтую ячейку $J$2 не сместилась. Поэтому для точного копирования формул можно временно перевести все ссылки во всех формулах в абсолютные. Нужно будет выделить каждую формулу в строке формул и нажать клавишу F4:
При большом количестве ячеек этот вариант, понятное дело, отпадает — слишком трудоемко.
Способ 2. Временная деактивация формул
Чтобы формулы при копировании не менялись, надо (временно) сделать так, чтобы Excel перестал их рассматривать как формулы. Это можно сделать, заменив на время копирования знак «равно» (=) на любой другой символ, не встречающийся обычно в формулах, например на «решетку» (#) или на пару амперсандов (&&). Для этого:
- Выделяем диапазон с формулами (в нашем примере D2:D8)
- Жмем Ctrl+H на клавиатуре или на вкладке Главная — Найти и выделить — Заменить (Home — Find&Select — Replace)
- В появившемся диалоговом окне вводим что ищем и на что заменяем и в Параметрах (Options) не забываем уточнить Область поиска — Формулы. Жмем Заменить все (Replace all).
- Копируем получившийся диапазон с деактивированными формулами в нужное место:
- Заменяем # на = обратно с помощью того же окна, возвращая функциональность формулам.
Способ 3. Копирование через Блокнот
Этот способ существенно быстрее и проще.
Нажмите сочетание клавиш Ctrl+Ё или кнопку Показать формулы на вкладке Формулы (Formulas — Show formulas), чтобы включить режим проверки формул — в ячейках вместо результатов начнут отображаться формулы, по которым они посчитаны:
Скопируйте наш диапазон D2:D8 и вставьте его в стандартный Блокнот:
Теперь выделите все вставленное (Ctrl+A), скопируйте в буфер еще раз (Ctrl+C) и вставьте на лист в нужное вам место:
Осталось только отжать кнопку Показать формулы (Show Formulas), чтобы вернуть Excel в обычный режим.
Примечание: этот способ иногда дает сбой на сложных таблицах с объединенными ячейками, но в подавляющем большинстве случаев — работает отлично.
Способ 4. Макрос
Если подобное копирование формул без сдвига ссылок вам приходится делать часто, то имеет смысл использовать для этого макрос. Нажмите сочетание клавиш Alt+F11 или кнопку Visual Basic на вкладке Разработчик (Developer), вставьте новый модуль через меню Insert — Module и скопируйте туда текст вот такого макроса:
Sub Copy_Formulas() Dim copyRange As Range, pasteRange As Range On Error Resume Next Set copyRange = Application.InputBox("Выделите ячейки с формулами, которые надо скопировать.", _ "Точное копирование формул", Default:=Selection.Address, Type:=8) If copyRange Is Nothing Then Exit Sub Set pasteRange = Application.InputBox("Теперь выделите диапазон вставки." & vbCrLf & vbCrLf & _ "Диапазон должен быть равен по размеру исходному " & vbCrLf & _ "диапазону копируемых ячеек.", "Точное копирование формул", _ Default:=Selection.Address, Type:=8) If pasteRange.Cells.Count <> copyRange.Cells.Count Then MsgBox "Диапазоны копирования и вставки разного размера!", vbExclamation, "Ошибка копирования" Exit Sub End If If pasteRange Is Nothing Then Exit Sub Else pasteRange.Formula = copyRange.Formula End If End Sub
Для запуска макроса можно воспользоваться кнопкой Макросы на вкладке Разработчик (Developer — Macros) или сочетанием клавиш Alt+F8. После запуска макрос попросит вас выделить диапазон с исходными формулами и диапазон вставки и произведет точное копирование формул автоматически:
Ссылки по теме
- Удобный просмотр формул и результатов одновременно
- Зачем нужен стиль ссылок R1C1 в формулах Excel
- Как быстро найти все ячейки с формулами
- Инструмент для точного копирования формул из надстройки PLEX
Владимир_Сар 58 / 57 / 13 Регистрация: 10.09.2009 Сообщений: 255 |
||||||||
1 |
||||||||
Подскажите, как копировать формулы с ячеек листа екселя на другой лист20.10.2009, 15:34. Показов 8094. Ответов 4 Метки нет (Все метки)
Пробовал по разному
копирует значение, но не формулу, потом попробовал по стандарту
Если слишком много ячеек копировать противно мерцает экран
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
20.10.2009, 15:34 |
4 |
EducatedFool 0 / 0 / 0 Регистрация: 28.09.2009 Сообщений: 88 |
||||
20.10.2009, 16:30 |
2 |
|||
0 |
58 / 57 / 13 Регистрация: 10.09.2009 Сообщений: 255 |
|
20.10.2009, 16:40 [ТС] |
3 |
Спасибо, правда долго копирует
0 |
Toxa33rus 3895 / 898 / 122 Регистрация: 16.04.2009 Сообщений: 1,824 |
||||
20.10.2009, 16:43 |
4 |
|||
Может так попробовать:
1 |
58 / 57 / 13 Регистрация: 10.09.2009 Сообщений: 255 |
|
20.10.2009, 16:48 [ТС] |
5 |
Спасибо этот вариант гораздо быстрее
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
20.10.2009, 16:48 |
5 |
Группа: Пользователи Ранг: Новичок Сообщений: 45
Замечаний: |
Здравствуйте, может мой вопрос уже изъезжен, но не могу найти решение.
Необходимо скопировать формулу из ячейки одного документа в ячейку другого документа.
Опишу кратко, код там большой но все упирается в следующий отрезок.
Допустим в ячейке есть формула A1+B1
[vba]
Код
Set WS1 = Workbooks.Item(«Договоры1.xlsm»).Sheets(«Договоры»)
Set WS2 = Workbooks.Item(«Договоры2.xlsm»).Sheets(«Договоры»)
WS1.Cells(1, 2).Copy: WS2.Cells(1, 2).PasteSpecial xlPasteValues ‘Копирую значения
WS1.Cells(1, 2).Copy: WS2.Cells(1, 2).PasteSpecial xlPasteFormulas ‘Копирую формулы
[/vba]
В итоге в файл «Договоры2» копируется ячейка, а формула в ней ссылается на ячейки файла «Договоры1»
с результатом ‘C:…Договоры1′!A1+C:…Договоры1’!B1
Как быть? нужно чтобы получилось A1+B1
Я так понимаю можно какой то приписать параметр может быть?
Предположим, вам надо было найти итоговые суммы только за январь и июнь. В этом случае, введя формулу в ячейку В6, любым известным способом скопируйте её в ячейку G6.
ПОДСКАЗКИ:
Можно воспользоваться классической операцией копирования.
Можно копировать формулу с помощью мышки.
В предыдущих двух случаях помимо формулы будут копироваться и форматы исходной ячейки. Для копирования одной лишь формулы (без форматов!) воспользуйтесь операцией СПЕЦИАЛЬНАЯ ВСТАВКА , включив в одноименном окне кнопку формулы.
Автосуммирование
Чаще всего при обработке табличных данных необходимо подсчитать различные суммы. Легче всего для этого воспользоваться инструментом (Автосумма).
Итак, для того чтобы познакомиться с автосуммированием, удалите содержимое ячеек В6:H6 . Затем:
- активизируйте ячейку В6;
- щелкните по инструменту Автосумма – . Excel “огляделся” вокруг и “нашел” над текущей ячейкой числа, расположенные в диапазоне В4:В5. В строке формул и в текущей ячейке появилась функция суммирования, а вокруг предлагаемого диапазона суммируемых ячеек побежала прерывистая дорожка.
- если вы согласны с предлагаемым диапазоном суммируемых ячеек, нажмите клавишу [Enter] (или щелкните по зеленой галочке). Если нет, — выделите новый диапазон и завершите ввод данных;
- скопируйте введенную формулу в ячейки С6:Н6.
Возможно вам это будет интересно!
2020-11-30
I have an existing VBA code that copies an Excel worksheet from my source workbook (Sourcewb
) into a new destination workbook (Destwb
) but pastes values only. I need a specific range (D31:E38
) in the Destwb
to include the formulas from the source workbook. I found this code:
Range("A1:I1105").Copy Sheets("Sheet2").Range("B2")
On this site (another question) that seems related but don’t know how to modify it to work in my application. I have added a comment line » ‘Insert total formulas in Calc sheet» for where I think the additional code would go. Here is my existing code:
Set Sourcewb = ActiveWorkbook
'Copy the sheet to a new workbook
Sheets("Calculation").Copy
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2013
FileExtStr = ".xlsx": FileFormatNum = 51
End If
End With
'Change all cells in the worksheet to values if you want
With Destwb.Sheets(1).UsedRange
Application.CutCopyMode = False
ActiveSheet.Unprotect
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
.Cells(1).Select
End With
Application.CutCopyMode = False
'Insert total formulas in Calc sheet
'Save the new workbook and close it
TempFilePath = Sheets("Calculation").Range("L4").Value
TempFileName = Range("L3").Value
With Destwb
.SaveAs TempFilePath & "" & TempFileName & FileExtStr, FileFormat:=FileFormatNum
.Close SaveChanges:=True
End With
MsgBox "You can find the new file in " & TempFilePath
shA.t
16.4k5 gold badges53 silver badges111 bronze badges
asked May 12, 2015 at 15:08
1
You could copy the whole thing first, like you are doing and then overwrite the cells in Destwb
D31:E38
with the formulas from the cells in Sourcewb
. Assuming the range of interest in Sourcewb
is «D31:E38
» and that the destination range and source range are the same size, you could do the following:
'Copy all cells
'Your code here
'New code
set formulaRngFromSource = Sourcewb.Sheets("Calculation").Range("D31:E38")
set formulaRngToDest = Destwb.Sheets(1).Range("D31:E38")
i = 1
for each range in formulaRngFromSource
formulaRngToDest(i).Formula = range.Formula
i = i + 1
next range
shA.t
16.4k5 gold badges53 silver badges111 bronze badges
answered May 12, 2015 at 15:28
deasadeasa
60610 silver badges24 bronze badges
0
You can try with: ActiveSheet.PasteSpecial Paste:=xlFormulas
ActiveSheet.Unprotect
...
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
.Cells.PasteSpecial xlFormulas
.Cells(1).Select
End With
shA.t
16.4k5 gold badges53 silver badges111 bronze badges
answered May 12, 2015 at 15:21
JavyskJavysk
3512 silver badges16 bronze badges
Download Article
Download Article
- Using Find and Replace
- Filling a Column or Row
- Pasting a Formula into Multiple Cells
- Using Relative and Absolute Cell References
- Video
- Q&A
- Tips
- Warnings
|
|
|
|
|
|
|
Excel makes it easy to copy your formula across an entire row or column, but you don’t always get the results you want. If you end up with unexpected results, or those awful #REF and /DIV0 errors, it can be extremely frustrating. But don’t worry—you won’t need to edit your 5,000 line spreadsheet cell-by-cell. This wikiHow teaches you easy ways to copy formulas to other cells.
-
1
Open your workbook in Excel. Sometimes, you have a large spreadsheet full of formulas, and you want to copy them exactly. Changing everything to absolute cell references would be tedious, especially if you just want to change them back again afterward. Use this method to quickly move formulas with relative cell references elsewhere without changing the references.[1]
In our example spreadsheet, we want to copy the formulas from column C to column D without changing anything.Example Spreadsheet
Column A Column B Column C Column D row 1 944
Frogs
=A1/2
row 2 636
Toads
=A2/2
row 3 712
Newts
=A3/2
row 4 690
Snakes
=A4/2
- If you’re just trying to copy the formula in a single cell, skip to the last step («Try alternate methods») in this section.
-
2
Press Ctrl+H to open the Find window. The shortcut is the same on Windows and macOS.
Advertisement
-
3
Find and replace «=» with another character. Type «=» into the «Find what» field, and then type a different character into the «Replace with» box. Click Replace All to turn all formulas (which always begin with an equal’s sign) into text strings beginning with some other character. Always use a character that you have not used in your spreadsheet. For example, replace it with # or &, or a longer string of characters, such as ##&.
Example Spreadsheet
Column A Column B Column C Column D row 1 944
Frogs
##&A1/2
row 2 636
Toads
##&A2/2
row 3 712
Newts
##&A3/2
row 4 690
Snakes
##&A4/2
- Do not use the characters * or ?, since these will make later steps more difficult.
-
4
Copy and paste the cells. Highlight the cells you want to copy, and then press Ctrl + C (PC) or Cmd + C (Mac) to copy them. Then, select the cells you want to paste into, and press Ctrl + V (PC) or Cmd + V (Mac) to paste. Since they are no longer interpreted as formulas, they will be copied exactly.
Example Spreadsheet
Column A Column B Column C Column D row 1 944
Frogs
##&A1/2
##&A1/2
row 2 636
Toads
##&A2/2
##&A2/2
row 3 712
Newts
##&A3/2
##&A3/2
row 4 690
Snakes
##&A4/2
##&A4/2
-
5
Use Find & Replace again to reverse the change. Now that you have the formulas where you want them, use «Replace All» again to reverse your change. In our example, we’ll look for the character string «##&» and replace it with «=» again, so those cells become formulas once again. You can now continue editing your spreadsheet as usual:
Example Spreadsheet
Column A Column B Column C Column D row 1 944
Frogs
=A1/2
=A1/2
row 2 636
Toads
=A2/2
=A2/2
row 3 712
Newts
=A3/2
=A3/2
row 4 690
Snakes
=A4/2
=A4/2
-
6
Try alternate methods. If the method described above doesn’t work for some reason, or if you are worried about accidentally changing other cell contents with the «Replace all» option, there are a couple other things you can try:
- To copy a single cell’s formula without changing references, select the cell, then copy the formula shown in the formula bar near the top of the window (not in the cell itself). Press Esc to close the formula bar, then paste the formula wherever you need it.
- Press Ctrl and ` (usually on the same key as ~) to put the spreadsheet in formula view mode. Copy the formulas and paste them into a text editor such as Notepad or TextEdit. Copy them again, then paste them back into the spreadsheet at the desired location. Then, press Ctrl and ` again to switch back to regular viewing mode.
Advertisement
-
1
Type a formula into a blank cell. Excel makes it easy to propagate a formula down a column or across a row by «filling» the cells. As with any formula, start with an = sign, then use whichever functions or arithmetic you’d like. We’ll use a simple example spreadsheet, and add column A and column B together. Press Enter or Return to calculate the formula.
Example Spreadsheet
Column A Column B Column C row 1 10
9
19
row 2 20
8
row 3 30
7
row 4 40
6
-
2
Click the lower right corner of the cell with the formula you want to copy. The cursor will become a bold + sign.
-
3
Click and drag the cursor across the column or row you’re copying to. The formula you entered will automatically be entered into the cells you’ve highlighted. Relative cell references will automatically update to refer to the cell in the same relative position rather than stay exactly the same. Here’s our example spreadsheet, showing the formulas used and the results displayed:
Example Spreadsheet
Column A Column B Column C row 1 10
9
=A1+B1
row 2 20
8
=A2+B2
row 3 30
7
=A3+B3
row 4 40
6
=A4+B4
Example Spreadsheet
Column A Column B Column C row 1 10
9
19
row 2 20
8
28
row 3 30
7
37
row 4 40
6
46
- You can also double-click the plus sign to fill the entire column instead of dragging. Excel will stop filling out the column if it sees an empty cell. If the reference data contains a gap, you will have to repeat this step to fill out the column below the gap.
- Another way to fill the entire column with the same formula is to select the cells directly below the one containing the formula and then press Ctrl + D.[2]
Advertisement
-
1
Type the formula into one cell. As with any formula, start with an = sign, then use whichever functions or arithmetic you’d like. We’ll use a simple example spreadsheet, and add column A and column B together. When you press Enter or Return, the formula will calculate.
Example Spreadsheet
Column A Column B Column C row 1 10
9
19
row 2 20
8
row 3 30
7
row 4 40
6
-
2
Select the cell and press Ctrl+C (PC) or ⌘ Command+C (Mac). This copies the formula to your clipboard.
-
3
Select the cells you want to copy the formula to. Click on one and drag up or down using your mouse or the arrow keys. Unlike with the column or row fill method, the cells you are copying the formula to do not need to be adjacent to the cell you are copying from. You can hold down the Control key while selecting to copy non-adjacent cells and ranges.
-
4
Press Ctrl+V (PC) or ⌘ Command+V (Mac) to paste. The formulas now appear in the selected cells.
Advertisement
-
1
Use a relative cell reference in a formula. In an Excel formula, a «cell reference» is the address a cell. You can type these in manually, or click on the cell you wish to use while you are entering a formula. For example, the following spreadsheet has a formula that references cell A2:
Relative References
Column A Column B Column C row 2 50
7
=A2*2
row 3 100
row 4 200
row 5 400
-
2
Understand why they’re called relative references. In an Excel formula, a relative reference uses the relative position of a cell address. In our example, C2 has the formula “=A2”, which is a relative reference to the value two cells to the left. If you copy the formula into C4, then it will still refer to two cells to the left, now showing “=A4”.
Relative References
Column A Column B Column C row 2 50
7
=A2*2
row 3 100
row 4 200
=A4*2
row 5 400
- This works for cells outside of the same row and column as well. If you copied the same formula from cell C1 into cell D6 (not shown), Excel would change the reference «A2» to a cell one column to the right (C→D) and 5 rows below (2→7), or «B7».
-
3
Use an absolute reference instead. Let’s say you don’t want Excel to automatically change your formula. Instead of using a relative cell reference, you can make it absolute by adding a $ symbol in front of the column or row that you want to keep the same, no matter where you copy the formula too.[3]
Here are a few example spreadsheets, showing the original formula in larger, bold text, and the result when you copy-paste it to other cells:-
Relative Column, Absolute Row (B$3): The formula has an absolute reference to row 3, so it always refers to row 3:
Column A Column B Column C row 1 50
7
=B$3
row 2 100
=A$3
=B$3
row 3 200
=A$3
=B$3
row 4 400
=A$3
=B$3
-
Absolute Column, Relative Row ($B1): The formula has an absolute reference to column B, so it always refers to column B.
Column A Column B Column C row 1 50
7
=$B1
row 2 100
=$B2
=$B2
row 3 200
=$B3
=$B3
row 4 400
=$B4
=$B4
-
Absolute Column & Row ($B$1): The formula has an absolute reference to column B of row 1, so it always refers to column B of row 1.
Column A Column B Column C row 1 50
7
=$B$1
row 2 100
=$B$1
=$B$1
row 3 200
=$B$1
=$B$1
row 4 400
=$B$1
=$B$1
-
Relative Column, Absolute Row (B$3): The formula has an absolute reference to row 3, so it always refers to row 3:
-
4
Use the F4 key to switch between absolute and relative. Highlight a cell reference in a formula by clicking it and press F4 to automatically add or remove $ symbols. Keep pressing F4 until the absolute or relative references you’d like are selected, then press Enter or Return.
Advertisement
Add New Question
-
Question
When I try to pull down formula, it stays the same and does not change with row, what can I do?
Go to Formulas, Calculation Options, and change them from Manual to Automatic.
-
Question
When I click and drag, it copies the format also. I don’t want to copy the format, just the formula?
Krisztian Toth
Community Answer
Right after the drag there should be an icon in the lower right corner of the highlighted area. Hover over that and select from the various fill options, among which you can find an option to fill without format.
-
Question
How do I copy a date formula I have created (that includes the week day as well as date) so that it runs in sequence?
Krisztian Toth
Community Answer
Double click into the cell, copy your formula, double click into the destination cell, then press Ctrl+V or Command+V.
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
If you copy a formula to a new cell and see a green triangle, Excel has detected a possible error. Examine the formula carefully to see if anything went wrong.[4]
-
If you accidentally did replace the = character with ? or * in the «copying a formula exactly» method, searching for «?» or «*» will not give you the results you expect. Correct this by searching for «~?» or for «~*» instead.[5]
-
Select a cell and press Ctrl‘ (apostrophe) to fill it with the formula directly above it.
Thanks for submitting a tip for review!
Advertisement
-
Different versions of Excel may not show exactly the same screenshots in the same ways as are displayed here.
Advertisement
References
About This Article
Article SummaryX
To copy a formula into multiple adjoining cells in Microsoft Excel, type the formula into a cell, and then press Enter or Return to calculate it. Hover your mouse cursor over the bottom-right corner of the cell so the cursor turns to a crosshair, then drag the crosshair down to copy the formula to other cells in the column. If you’d rather copy the formula to cells in a row, drag the crosshair left or right.
To copy a formula to cells that aren’t touching the formula cell, click the cell once to select it, and then press Control + C (on a PC) or Command + C (on a Mac) to copy the formula. Now, select the cell or cells you want to copy the formula to, then press Control + V (on a PC) or Command + V (on a Mac) to paste it into the selected cells.
Did this summary help you?
Thanks to all authors for creating a page that has been read 513,858 times.