Относительные адреса vba excel

We have two options to refer a cell in excel VBA Absolute references and Relative references.  Default Excel records macro in Absolute mode.

In this article, we learn about Relative references in excel VBA.  We select a cell “A1”, turn on “Use Relative Reference” and record a macro to type some text in cells B2:B4.  

Since we turn on the “Relative reference” option.  Macro considers the number of rows and number of columns from active cells.  In our example, we select cell A1 and start type B2 which is to move one column and one row from A1 (Active cell).

Implementation:

Follow the below steps to implement relative reference in Excel Macros:

Step 1: Open Excel and Select Cell “A1”.

Step 2: Go to “Developer” Tab >> Press “Use Relative References” >> Click “Record Macro” .

Step 3: Enter the Macro name “relativeReference” and Press “OK”.

Step 4: Type “Australia” in cell B2  

Step 5: Type “Brazil” in cell B3

Step 6: Type “Mexico” in cell B4

Step 7: Select cell B5 and Press “Stop Recording”  

VBA Code (Recorded):

Sub relativeReference()
    ActiveCell.Offset(1, 1).Range("A1").Select
    ActiveCell.FormulaR1C1 = "Australia"
    ActiveCell.Offset(1, 0).Range("A1").Select
    ActiveCell.FormulaR1C1 = "Brazil"
    ActiveCell.Offset(1, 0).Range("A1").Select
    ActiveCell.FormulaR1C1 = "Mexico"
    ActiveCell.Offset(1, 0).Range("A1").Select
End Sub 

Step 8: You just delete the contents in cells B2:B4, Select Cell B1.

Step 9: Go to View >> Macros >> View Macros – to popup Macro dialog box [keyboard shortcut – Alt+F8].

Step 10: Select Macro from list (eg. relativeReference) and Press “Run”.

Output:

The active cell is B1 and run the macro.  So, the outputs (C2:C4) are placed one row and one column from the active cell B1.

Хитрости »

19 Февраль 2021              6743 просмотров


Использование относительных ссылок в макросах


Если Вы уже записывали макросы обработки таблиц, то наверняка сталкивались с ситуацией, когда макросом в таблицу добавляется столбец с формулами, которые потом необходимо распространить на все строки. Но если количество строк в таблице изменяется, то макрос работает некорректно: если строк стало больше, то формулы проставляются не на все строки, а если строк стало меньше – то появляются строки с лишними формулами.
Если Вы еще не знаете что такое макрос и как его записывать и воспроизводить, то рекомендуется сначала ознакомиться со статьей: Что такое макрос и где его искать?
К примеру, возьмем таблицу такого вида:
Исходная таблица
В конце таблицы нам необходимо добавить столбец «Стоимость», прописав в нем нехитрую формулу перемножения количества на цену:
=F2*G2
Перед записью макроса выделяем ячейку H1. При обычной записи макроса наши шаги такие:
1. Выделили I1
2. Записали в неё заголовок «Стоимость»
3. Перешли в I2
4. Записали формулу: =F2*G2
5. Распространили формулу до конца таблицы (через автозаполнение или путем копирования ячейки с формулой и вставки в остальные ячейки)
Макрос работает отлично. Пока количество строк не изменится. Если при записи макроса в таблице было 319 строк, а потом добавилось еще 20, то записанный макрос создаст формулу только в первых 319 строках. Все дело в том, что при обычной записи макрос использует абсолютную адресацию ячеек. Т.е. в нем каждый наш шаг обозначает выделение ячеек с конкретно указанным адресом (I1, I2, I319 и т.д.):
Пример абсолютных ссылок
Как выйти из такой ситуации? Все не слишком сложно. В группе кнопок код на вкладке Разработчик есть кнопка «Относительные ссылки». Если нажать её до записи макроса(или во время), то ссылки на ячейки будут уже запоминаться не как конкретный адрес, а как смещение относительно последней выделенной ячейки.
Например, запишем два простых макроса, которые будут делать одно и то же действие – перемещение вниз таблицы и выделение ячеек от нижней до верхней. Только первый макрос будет записан обычным способом, а перед записью второго мы нажмем кнопку «Относительные ссылки». Наши действия будут следующими (одинаковыми для обоих макросов):
1. До записи макроса выделяем ячейку I2
2. Начинаем запись макроса
3. Выделяем ячейку H2
4. Комбинацией клавиш Ctrl+↓(стрелка вниз) перемещаемся вниз таблицы
5. Стрелка вправо (т.е. выделяем последнюю ячейку в столбце I)
6. Комбинацией клавиш Ctrl+Shift+↑(стрелка вверх) выделяем столбец I от последней ячейки до первой
7. Завершаем запись макроса
Теперь можно посмотреть на код обоих макросов:
Сравнение кодов
Отличия очевидны: в первом используется обращение к ячейкам по их конкретным адресам. Во втором же все действия происходят относительно последней выделенной ячейки(на Range(«A1») не обращаем внимания – это из другой оперы и если их удалить ничего не изменится). Из этого можно сделать вывод, что для создания гибких универсальных макросов с использованием относительных ссылок необходимо как можно меньше использовать мышку и максимально стараться применять горячие клавиши. Попробую пояснить почему: когда мы применяем то же автозаполнение (наведение курсора мыши на нижний правый угол ячейки и протягивание вниз или двойной щелчок левой кнопкой мыши) – оно применяется к конкретно определенному количеству ячеек. Т.е. даже относительные ссылки не помогут заполнить его формулами, как того требует наша изначальная задача. Но если использовать горячие клавиши перемещения и выделения (Ctrl+стрелка и Ctrl+Shift+стрелка), то мы можем создать макрос, которому уже будет не важно сколько строк в нашей таблице. Чтобы в этом убедиться, запишем макрос из начала статьи, но уже с использованием относительных ссылок и исключительно клавиш для перемещения. Наши действия:
1. Перед записью макроса выделяем ячейку H1
2. Начали запись макроса
3. Нажимаем кнопку Относительные ссылки(если она еще не нажата)
4. Выделяем I1
5. Записываем в неё заголовок «Стоимость»
6. Переходим в I2
7. Записываем в I2 формулу: =F2*G2
8. Комбинацией клавиш Ctrl+C(или при помощи контекстного меню мыши) копируем ячейку с формулой
9. Стрелкой вправо перемещаемся в ячейку H2
10. Комбинацией клавиш Ctrl+↓(стрелка вниз) перемещаемся вниз таблицы
11. Стрелка вправо (т.е. выделяем последнюю ячейку в столбце I)
12. Комбинацией клавиш Ctrl+Shift+↑(стрелка вверх) выделяем столбец I от последней ячейки до первой
13. Комбинацией клавиш Ctrl+V вставляем скопированную формулу
14. Нажимаем Esc для сброса буфера обмена
15. Запись макроса можно завершить
Если теперь попробовать применить такой макрос к таблице, у которой строк больше или меньше, чем было при записи макроса – все пройдет идеально. Макрос создаст столбец и запишет в нем формулу только на нужное количество строк.
Более того. Если наша таблица находится уже в другом листе и даже начинается не с первой ячейки, а где-то в середине:
Хаотично расположенная таблица
Нам достаточно будет выделить ячейку заголовка последнего столбца(K5) и запустить наш макрос. Он без проблем добавит столбец с формулой в нужном месте и на все строки. Макрос же без использования относительных ссылок в такой ситуации спасует по полной: он создаст формулы начиная с ячейки I2 и до заголовка, только испортив таблицу и не сделав ничего полезного.
Так же хочу дополнить, что Относительные ссылки играют роль исключительно во время записи макроса. Во время воспроизведения совершенно не важно включены они или нет. Плюс можно(а иногда и нужно) комбинировать во время записи макросов режим относительных ссылок с обычным режимом. Например, когда столбцов в таблице у нас всегда одинаковое количество и таблица всегда в одном месте, и столбец мы добавляем всегда в столбец I. Но формулы при этом надо протягивать на разное количество строк. Тогда можно начать запись макроса обычным режимом, а после того, как записали название столбца — включить режим относительных ссылок, чтобы определение последней ячейки таблицы не зависело от количества строк в этой таблице.


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

“It is a capital mistake to theorize before one has data”- Sir Arthur Conan Doyle

This post covers everything you need to know about using Cells and Ranges in VBA. You can read it from start to finish as it is laid out in a logical order. If you prefer you can use the table of contents below to go to a section of your choice.

Topics covered include Offset property, reading values between cells, reading values to arrays and formatting cells.

A Quick Guide to Ranges and Cells

Function Takes Returns Example Gives

Range

cell address multiple cells .Range(«A1:A4») $A$1:$A$4
Cells row, column one cell .Cells(1,5) $E$1
Offset row, column multiple cells Range(«A1:A2»)
.Offset(1,2)
$C$2:$C$3
Rows row(s) one or more rows .Rows(4)
.Rows(«2:4»)
$4:$4
$2:$4
Columns column(s) one or more columns .Columns(4)
.Columns(«B:D»)
$D:$D
$B:$D

Download the Code

 

The Webinar

If you are a member of the VBA Vault, then click on the image below to access the webinar and the associated source code.

(Note: Website members have access to the full webinar archive.)

vba ranges video

Introduction

This is the third post dealing with the three main elements of VBA. These three elements are the Workbooks, Worksheets and Ranges/Cells. Cells are by far the most important part of Excel. Almost everything you do in Excel starts and ends with Cells.

 
Generally speaking, you do three main things with Cells

  1. Read from a cell.
  2. Write to a cell.
  3. Change the format of a cell.

 
Excel has a number of methods for accessing cells such as Range, Cells and Offset.These can cause confusion as they do similar things and can lead to confusion

In this post I will tackle each one, explain why you need it and when you should use it.

 
Let’s start with the simplest method of accessing cells – using the Range property of the worksheet.

Important Notes

I have recently updated this article so that is uses Value2.

You may be wondering what is the difference between Value, Value2 and the default:

' Value2
Range("A1").Value2 = 56

' Value
Range("A1").Value = 56

' Default uses value
Range("A1") = 56

 
Using Value may truncate number if the cell is formatted as currency. If you don’t use any property then the default is Value.

It is better to use Value2 as it will always return the actual cell value(see this article from Charle Williams.)

The Range Property

The worksheet has a Range property which you can use to access cells in VBA. The Range property takes the same argument that most Excel Worksheet functions take e.g. “A1”, “A3:C6” etc.

The following example shows you how to place a value in a cell using the Range property.

' https://excelmacromastery.com/
Public Sub WriteToCell()

    ' Write number to cell A1 in sheet1 of this workbook
    ThisWorkbook.Worksheets("Sheet1").Range("A1").Value2 = 67

    ' Write text to cell A2 in sheet1 of this workbook
    ThisWorkbook.Worksheets("Sheet1").Range("A2").Value2 = "John Smith"

    ' Write date to cell A3 in sheet1 of this workbook
    ThisWorkbook.Worksheets("Sheet1").Range("A3").Value2 = #11/21/2017#

End Sub

 
As you can see Range is a member of the worksheet which in turn is a member of the Workbook. This follows the same hierarchy as in Excel so should be easy to understand. To do something with Range you must first specify the workbook and worksheet it belongs to.

For the rest of this post I will use the code name to reference the worksheet.

code name worksheet

 
 
The following code shows the above example using the code name of the worksheet i.e. Sheet1 instead of ThisWorkbook.Worksheets(“Sheet1”).

' https://excelmacromastery.com/
Public Sub UsingCodeName()

    ' Write number to cell A1 in sheet1 of this workbook
    Sheet1.Range("A1").Value2 = 67

    ' Write text to cell A2 in sheet1 of this workbook
    Sheet1.Range("A2").Value2 = "John Smith"

    ' Write date to cell A3 in sheet1 of this workbook
    Sheet1.Range("A3").Value2 = #11/21/2017#

End Sub

You can also write to multiple cells using the Range property

' https://excelmacromastery.com/
Public Sub WriteToMulti()

    ' Write number to a range of cells
    Sheet1.Range("A1:A10").Value2 = 67

    ' Write text to multiple ranges of cells
    Sheet1.Range("B2:B5,B7:B9").Value2 = "John Smith"

End Sub

 
You can download working examples of all the code from this post from the top of this article.
 

The Cells Property of the Worksheet

The worksheet object has another property called Cells which is very similar to range. There are two differences

  1. Cells returns a range of one cell only.
  2. Cells takes row and column as arguments.

 
The example below shows you how to write values to cells using both the Range and Cells property

' https://excelmacromastery.com/
Public Sub UsingCells()

    ' Write to A1
    Sheet1.Range("A1").Value2 = 10
    Sheet1.Cells(1, 1).Value2  = 10

    ' Write to A10
    Sheet1.Range("A10").Value2 = 10
    Sheet1.Cells(10, 1).Value2  = 10

    ' Write to E1
    Sheet1.Range("E1").Value2 = 10
    Sheet1.Cells(1, 5).Value2  = 10

End Sub

 
You may be wondering when you should use Cells and when you should use Range. Using Range is useful for accessing the same cells each time the Macro runs.

For example, if you were using a Macro to calculate a total and write it to cell A10 every time then Range would be suitable for this task.

Using the Cells property is useful if you are accessing a cell based on a number that may vary. It is easier to explain this with an example.

 
In the following code, we ask the user to specify the column number. Using Cells gives us the flexibility to use a variable number for the column.

' https://excelmacromastery.com/
Public Sub WriteToColumn()

    Dim UserCol As Integer
    
    ' Get the column number from the user
    UserCol = Application.InputBox(" Please enter the column...", Type:=1)
    
    ' Write text to user selected column
    Sheet1.Cells(1, UserCol).Value2 = "John Smith"

End Sub

 
In the above example, we are using a number for the column rather than a letter.

To use Range here would require us to convert these values to the letter/number  cell reference e.g. “C1”. Using the Cells property allows us to provide a row and a column number to access a cell.

Sometimes you may want to return more than one cell using row and column numbers. The next section shows you how to do this.

Using Cells and Range together

As you have seen you can only access one cell using the Cells property. If you want to return a range of cells then you can use Cells with Ranges as follows

' https://excelmacromastery.com/
Public Sub UsingCellsWithRange()

    With Sheet1
        ' Write 5 to Range A1:A10 using Cells property
        .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5

        ' Format Range B1:Z1 to be bold
        .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True

    End With

End Sub

 
As you can see, you provide the start and end cell of the Range. Sometimes it can be tricky to see which range you are dealing with when the value are all numbers. Range has a property called Address which displays the letter/ number cell reference of any range. This can come in very handy when you are debugging or writing code for the first time.

 
In the following example we print out the address of the ranges we are using:

' https://excelmacromastery.com/
Public Sub ShowRangeAddress()

    ' Note: Using underscore allows you to split up lines of code
    With Sheet1

        ' Write 5 to Range A1:A10 using Cells property
        .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5
        Debug.Print "First address is : " _
            + .Range(.Cells(1, 1), .Cells(10, 1)).Address

        ' Format Range B1:Z1 to be bold
        .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
        Debug.Print "Second address is : " _
            + .Range(.Cells(1, 2), .Cells(1, 26)).Address

    End With

End Sub

 
In the example I used Debug.Print to print to the Immediate Window. To view this window select View->Immediate Window(or Ctrl G)

 
ImmediateWindow

 
ImmediateSampeText

 
You can download all the code for this post from the top of this article.
 

The Offset Property of Range

Range has a property called Offset. The term Offset refers to a count from the original position. It is used a lot in certain areas of programming. With the Offset property you can get a Range of cells the same size and a certain distance from the current range. The reason this is useful is that sometimes you may want to select a Range based on a certain condition. For example in the screenshot below there is a column for each day of the week. Given the day number(i.e. Monday=1, Tuesday=2 etc.) we need to write the value to the correct column.

 
VBA Offset

 
We will first attempt to do this without using Offset.

' https://excelmacromastery.com/
' This sub tests with different values
Public Sub TestSelect()

    ' Monday
    SetValueSelect 1, 111.21
    ' Wednesday
    SetValueSelect 3, 456.99
    ' Friday
    SetValueSelect 5, 432.25
    ' Sunday
    SetValueSelect 7, 710.17

End Sub

' Writes the value to a column based on the day
Public Sub SetValueSelect(lDay As Long, lValue As Currency)

    Select Case lDay
        Case 1: Sheet1.Range("H3").Value2 = lValue
        Case 2: Sheet1.Range("I3").Value2 = lValue
        Case 3: Sheet1.Range("J3").Value2 = lValue
        Case 4: Sheet1.Range("K3").Value2 = lValue
        Case 5: Sheet1.Range("L3").Value2 = lValue
        Case 6: Sheet1.Range("M3").Value2 = lValue
        Case 7: Sheet1.Range("N3").Value2 = lValue
    End Select

End Sub

 
As you can see in the example, we need to add a line for each possible option. This is not an ideal situation. Using the Offset Property provides a much cleaner solution

' https://excelmacromastery.com/
' This sub tests with different values
Public Sub TestOffset()

    DayOffSet 1, 111.01
    DayOffSet 3, 456.99
    DayOffSet 5, 432.25
    DayOffSet 7, 710.17

End Sub

Public Sub DayOffSet(lDay As Long, lValue As Currency)

    ' We use the day value with offset specify the correct column
    Sheet1.Range("G3").Offset(, lDay).Value2 = lValue

End Sub

 
As you can see this solution is much better. If the number of days in increased then we do not need to add any more code. For Offset to be useful there needs to be some kind of relationship between the positions of the cells. If the Day columns in the above example were random then we could not use Offset. We would have to use the first solution.

 
One thing to keep in mind is that Offset retains the size of the range. So .Range(“A1:A3”).Offset(1,1) returns the range B2:B4. Below are some more examples of using Offset

' https://excelmacromastery.com/
Public Sub UsingOffset()

    ' Write to B2 - no offset
    Sheet1.Range("B2").Offset().Value2 = "Cell B2"

    ' Write to C2 - 1 column to the right
    Sheet1.Range("B2").Offset(, 1).Value2 = "Cell C2"

    ' Write to B3 - 1 row down
    Sheet1.Range("B2").Offset(1).Value2 = "Cell B3"

    ' Write to C3 - 1 column right and 1 row down
    Sheet1.Range("B2").Offset(1, 1).Value2 = "Cell C3"

    ' Write to A1 - 1 column left and 1 row up
    Sheet1.Range("B2").Offset(-1, -1).Value2 = "Cell A1"

    ' Write to range E3:G13 - 1 column right and 1 row down
    Sheet1.Range("D2:F12").Offset(1, 1).Value2 = "Cells E3:G13"

End Sub

Using the Range CurrentRegion

CurrentRegion returns a range of all the adjacent cells to the given range.

In the screenshot below you can see the two current regions. I have added borders to make the current regions clear.

VBA CurrentRegion

A row or column of blank cells signifies the end of a current region.

You can manually check the CurrentRegion in Excel by selecting a range and pressing Ctrl + Shift + *.

If we take any range of cells within the border and apply CurrentRegion, we will get back the range of cells in the entire area.

For example
Range(“B3”).CurrentRegion will return the range B3:D14
Range(“D14”).CurrentRegion will return the range B3:D14
Range(“C8:C9”).CurrentRegion will return the range B3:D14
and so on

How to Use

We get the CurrentRegion as follows

' Current region will return B3:D14 from above example
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

Read Data Rows Only

Read through the range from the second row i.e.skipping the header row

' Current region will return B3:D14 from above example
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

' Start at row 2 - row after header
Dim i As Long
For i = 2 To rg.Rows.Count
    ' current row, column 1 of range
    Debug.Print rg.Cells(i, 1).Value2
Next i

Remove Header

Remove header row(i.e. first row) from the range. For example if range is A1:D4 this will return A2:D4

' Current region will return B3:D14 from above example
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

' Remove Header
Set rg = rg.Resize(rg.Rows.Count - 1).Offset(1)

' Start at row 1 as no header row
Dim i As Long
For i = 1 To rg.Rows.Count
    ' current row, column 1 of range
    Debug.Print rg.Cells(i, 1).Value2
Next i

 

Using Rows and Columns as Ranges

If you want to do something with an entire Row or Column you can use the Rows or Columns property of the Worksheet. They both take one parameter which is the row or column number you wish to access

' https://excelmacromastery.com/
Public Sub UseRowAndColumns()

    ' Set the font size of column B to 9
    Sheet1.Columns(2).Font.Size = 9

    ' Set the width of columns D to F
    Sheet1.Columns("D:F").ColumnWidth = 4

    ' Set the font size of row 5 to 18
    Sheet1.Rows(5).Font.Size = 18

End Sub

Using Range in place of Worksheet

You can also use Cells, Rows and Columns as part of a Range rather than part of a Worksheet. You may have a specific need to do this but otherwise I would avoid the practice. It makes the code more complex. Simple code is your friend. It reduces the possibility of errors.

 
The code below will set the second column of the range to bold. As the range has only two rows the entire column is considered B1:B2

' https://excelmacromastery.com/
Public Sub UseColumnsInRange()

    ' This will set B1 and B2 to be bold
    Sheet1.Range("A1:C2").Columns(2).Font.Bold = True

End Sub

 
You can download all the code for this post from the top of this article.
 

Reading Values from one Cell to another

In most of the examples so far we have written values to a cell. We do this by placing the range on the left of the equals sign and the value to place in the cell on the right. To write data from one cell to another we do the same. The destination range goes on the left and the source range goes on the right.

 
The following example shows you how to do this:

' https://excelmacromastery.com/
Public Sub ReadValues()

    ' Place value from B1 in A1
    Sheet1.Range("A1").Value2 = Sheet1.Range("B1").Value2

    ' Place value from B3 in sheet2 to cell A1
    Sheet1.Range("A1").Value2 = Sheet2.Range("B3").Value2

    ' Place value from B1 in cells A1 to A5
    Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1").Value2

    ' You need to use the "Value" property to read multiple cells
    Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1:B5").Value2

End Sub

 
As you can see from this example it is not possible to read from multiple cells. If you want to do this you can use the Copy function of Range with the Destination parameter

' https://excelmacromastery.com/
Public Sub CopyValues()

    ' Store the copy range in a variable
    Dim rgCopy As Range
    Set rgCopy = Sheet1.Range("B1:B5")

    ' Use this to copy from more than one cell
    rgCopy.Copy Destination:=Sheet1.Range("A1:A5")

    ' You can paste to multiple destinations
    rgCopy.Copy Destination:=Sheet1.Range("A1:A5,C2:C6")

End Sub

 
The Copy function copies everything including the format of the cells. It is the same result as manually copying and pasting a selection. You can see more about it in the Copying and Pasting Cells section.

Using the Range.Resize Method

When copying from one range to another using assignment(i.e. the equals sign), the destination range must be the same size as the source range.

Using the Resize function allows us to resize a range to a given number of rows and columns.

For example:
 

' https://excelmacromastery.com/
Sub ResizeExamples()
 
    ' Prints A1
    Debug.Print Sheet1.Range("A1").Address

    ' Prints A1:A2
    Debug.Print Sheet1.Range("A1").Resize(2, 1).Address

    ' Prints A1:A5
    Debug.Print Sheet1.Range("A1").Resize(5, 1).Address
    
    ' Prints A1:D1
    Debug.Print Sheet1.Range("A1").Resize(1, 4).Address
    
    ' Prints A1:C3
    Debug.Print Sheet1.Range("A1").Resize(3, 3).Address
    
End Sub

 
When we want to resize our destination range we can simply use the source range size.

In other words, we use the row and column count of the source range as the parameters for resizing:

' https://excelmacromastery.com/
Sub Resize()

    Dim rgSrc As Range, rgDest As Range
    
    ' Get all the data in the current region
    Set rgSrc = Sheet1.Range("A1").CurrentRegion

      ' Get the range destination
    Set rgDest = Sheet2.Range("A1")
    Set rgDest = rgDest.Resize(rgSrc.Rows.Count, rgSrc.Columns.Count)
    
    rgDest.Value2 = rgSrc.Value2

End Sub

 
We can do the resize in one line if we prefer:

' https://excelmacromastery.com/
Sub ResizeOneLine()

    Dim rgSrc As Range
    
    ' Get all the data in the current region
    Set rgSrc = Sheet1.Range("A1").CurrentRegion
    
    With rgSrc
        Sheet2.Range("A1").Resize(.Rows.Count, .Columns.Count).Value2 = .Value2
    End With
    
End Sub

Reading Values to variables

We looked at how to read from one cell to another. You can also read from a cell to a variable. A variable is used to store values while a Macro is running. You normally do this when you want to manipulate the data before writing it somewhere. The following is a simple example using a variable. As you can see the value of the item to the right of the equals is written to the item to the left of the equals.

' https://excelmacromastery.com/
Public Sub UseVariables()

    ' Create
    Dim number As Long

    ' Read number from cell
    number = Sheet1.Range("A1").Value2

    ' Add 1 to value
    number = number + 1

    ' Write new value to cell
    Sheet1.Range("A2").Value2 = number

End Sub

 
To read text to a variable you use a variable of type String:

' https://excelmacromastery.com/
Public Sub UseVariableText()

    ' Declare a variable of type string
    Dim text As String

    ' Read value from cell
    text = Sheet1.Range("A1").Value2

    ' Write value to cell
    Sheet1.Range("A2").Value2 = text

End Sub

 
You can write a variable to a range of cells. You just specify the range on the left and the value will be written to all cells in the range.

' https://excelmacromastery.com/
Public Sub VarToMulti()

    ' Read value from cell
    Sheet1.Range("A1:B10").Value2 = 66

End Sub

 
You cannot read from multiple cells to a variable. However you can read to an array which is a collection of variables. We will look at doing this in the next section.

How to Copy and Paste Cells

If you want to copy and paste a range of cells then you do not need to select them. This is a common error made by new VBA users.

Note: We normally use Range.Copy when we want to copy formats, formulas, validation. If we want to copy values it is not the most efficient method.
I have written a complete guide to copying data in Excel VBA here.

 
You can simply copy a range of cells like this:

Range("A1:B4").Copy Destination:=Range("C5")

 
Using this method copies everything – values, formats, formulas and so on. If you want to copy individual items you can use the PasteSpecial property of range.

 
It works like this

Range("A1:B4").Copy
Range("F3").PasteSpecial Paste:=xlPasteValues
Range("F3").PasteSpecial Paste:=xlPasteFormats
Range("F3").PasteSpecial Paste:=xlPasteFormulas

 
The following table shows a full list of all the paste types

Paste Type
xlPasteAll
xlPasteAllExceptBorders
xlPasteAllMergingConditionalFormats
xlPasteAllUsingSourceTheme
xlPasteColumnWidths
xlPasteComments
xlPasteFormats
xlPasteFormulas
xlPasteFormulasAndNumberFormats
xlPasteValidation
xlPasteValues
xlPasteValuesAndNumberFormats

Reading a Range of Cells to an Array

You can also copy values by assigning the value of one range to another.

Range("A3:Z3").Value2 = Range("A1:Z1").Value2

 
The value of  range in this example is considered to be a variant array. What this means is that you can easily read from a range of cells to an array. You can also write from an array to a range of cells. If you are not familiar with arrays you can check them out in this post.  

 
The following code shows an example of using an array with a range:

' https://excelmacromastery.com/
Public Sub ReadToArray()

    ' Create dynamic array
    Dim StudentMarks() As Variant

    ' Read 26 values into array from the first row
    StudentMarks = Range("A1:Z1").Value2

    ' Do something with array here

    ' Write the 26 values to the third row
    Range("A3:Z3").Value2 = StudentMarks

End Sub

 
Keep in mind that the array created by the read is a 2 dimensional array. This is because a spreadsheet stores values in two dimensions i.e. rows and columns

Going through all the cells in a Range

Sometimes you may want to go through each cell one at a time to check value.

 
You can do this using a For Each loop shown in the following code

' https://excelmacromastery.com/
Public Sub TraversingCells()

    ' Go through each cells in the range
    Dim rg As Range
    For Each rg In Sheet1.Range("A1:A10,A20")
        ' Print address of cells that are negative
        If rg.Value < 0 Then
            Debug.Print rg.Address + " is negative."
        End If
    Next

End Sub

 
You can also go through consecutive Cells using the Cells property and a standard For loop.

 
The standard loop is more flexible about the order you use but it is slower than a For Each loop.

' https://excelmacromastery.com/
Public Sub TraverseCells()
 
    ' Go through cells from A1 to A10
    Dim i As Long
    For i = 1 To 10
        ' Print address of cells that are negative
        If Range("A" & i).Value < 0 Then
            Debug.Print Range("A" & i).Address + " is negative."
        End If
    Next
 
    ' Go through cells in reverse i.e. from A10 to A1
    For i = 10 To 1 Step -1
        ' Print address of cells that are negative
        If Range("A" & i) < 0 Then
            Debug.Print Range("A" & i).Address + " is negative."
        End If
    Next
 
End Sub

Formatting Cells

Sometimes you will need to format the cells the in spreadsheet. This is actually very straightforward. The following example shows you various formatting you can add to any range of cells

' https://excelmacromastery.com/
Public Sub FormattingCells()

    With Sheet1

        ' Format the font
        .Range("A1").Font.Bold = True
        .Range("A1").Font.Underline = True
        .Range("A1").Font.Color = rgbNavy

        ' Set the number format to 2 decimal places
        .Range("B2").NumberFormat = "0.00"
        ' Set the number format to a date
        .Range("C2").NumberFormat = "dd/mm/yyyy"
        ' Set the number format to general
        .Range("C3").NumberFormat = "General"
        ' Set the number format to text
        .Range("C4").NumberFormat = "Text"

        ' Set the fill color of the cell
        .Range("B3").Interior.Color = rgbSandyBrown

        ' Format the borders
        .Range("B4").Borders.LineStyle = xlDash
        .Range("B4").Borders.Color = rgbBlueViolet

    End With

End Sub

Main Points

The following is a summary of the main points

  1. Range returns a range of cells
  2. Cells returns one cells only
  3. You can read from one cell to another
  4. You can read from a range of cells to another range of cells.
  5. You can read values from cells to variables and vice versa.
  6. You can read values from ranges to arrays and vice versa
  7. You can use a For Each or For loop to run through every cell in a range.
  8. The properties Rows and Columns allow you to access a range of cells of these types

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

I need a relative cell address. i.e. «A2» not «$A$2»

When I use myAddress = Worksheets("Sheet1").Cells(1, 2).Address,
myAddress returns $B$2. I actually need the relative value B2.

Why, you ask? I knew you would ask… Because I want to then fill down the formula using that B2 cell address to all of the cells below it. And I don’t want each subsequent cell to refer to B2, but C2 then D2 and so on.

Community's user avatar

asked Jul 24, 2014 at 12:27

Kevin Scharnhorst's user avatar

myAddress = Worksheets("Sheet1").Cells(1, 2).Address(False, False)

answered Jul 24, 2014 at 12:29

GSerg's user avatar

7

В
Excel
строка,столбец,ячейка рассматриваются
как один объект. Для опеределения
диапазона используются различные
средства, задаваемые с помощью свойств
и методов.

Свойства:

Range
– определяет
диапазон ячеек

Cells

выбор
ячеек рабочего листа

ActiveCell
– 1
активная ячейка

Selection

указывает
выделенный объект

Для
абсолютной
ссылки на ячейки

используются два формата:

Формат
А1:ссылка из имени столбца и номера
строки

Формат
R1C1:R-номер
строки,C-номер
столбца(диапазон ячеек)

Для
создания относительной
ссылки

(изменяет адрес при копировании),задается
смещение по отношению к выделенной
ячейке. Смещение указывается в квадратных
скобках. Знак указывает направление
смещения.(R[-2]C-ссылка
на ячейку,расположенную на 2 строки
выше в том же столбце)

Ссылка
на одиночную ячейку
:

[объект].Range(“адрес
ячейки”)

Sheets(1).Range(“A7”)=34(записали
в ячейку)

[объект].Cells(строка,столбец),строка
столбец могут задаваться с помощью
переменных,что позволяет обращаться
к разеым ячейкам

Sheets(1).cells(i,j)

Операторы
– основные элементы кода. Последовательность
операторов образует процедуру. Различают
простые операторы и сложные(условия и
циклы).

Выражение
– комбинация знаков операции и
операндов,а так же скобки.

Назначение
любого выражения – получение некоторого
значения.

Kol>15
– логическое

Str*15/100
– арифметическое

Самые
простые операторы – операторы
присваивания. Они используются для
присвоения переменной нужного значения
соответствующего типа данных.

Fam=
«Иванов»

Билет
№25

1.
Признаки классификаций моделей.

1.
По области использования:-учебные(тренажёры,
обучающие программы)

-Опытные
модели(уменьш. или увелич. копии
проектируемого объекта)

-Научно-технические
модели(для исследования процессов или
явлений, напр. прибор для получения
грозового электрического разряда)

-Игровые
модели

-Имитационные
модели.

2.По
фактору времени

-статические(при
строительстве дома рассчитывают
прочность)

-динамические(противодействие
ветрам, движению грунтовых вод)

3.По
отрасли знаний(математич, биологич,
химические…)

4.По
форме представления

-Материальные-имеют
реальное воплощение, отраж. внешнее
св-во процессов и явл. оригинала.
напр.-глобус, муляжи..

-Информационные
мод.-целенаправленная отобранная
информ. об объекте, кот. отражает наиболее
существенные св-ва объекта.

по
степени формализации:

-образно-знаковые(географическая
карта) делятся на(геометрические мод,
структурные(схема), словесные(описание),
алгоритмические.

-знаковые
делятся(математ., специальные(ноты,
хим.формула, алгоритмические –
представляющие процесс в виде программы)

2.Общие
сведения о
VBA.
Принцип объектно-ориентированного
программирования(основные характеристики:
объект, класс, наследование и тд)

VBA
– подмножество языка программирования
Visual
Basic.
Basic
был разработан в 1963-1964 годы,
предназначен
для решения вычислительных задач в
режиме диалога. Реализован как
интерпретатор. 1991г.появился Visual Basic
(VB), включающий в себя:

—       
Средства визуального проектирования

—       
Элементы объектно-ориентированного
программирования.

VBA –
это версия визуального средства для
создания приложений. VBA является
объектно-ориентированным
языком программирования
.
Ключевой идеей объектно-ориентированного
программирования является объединение
данных и используемых для их обработки
функций в один объект.

Чтобы
проект можно было считать
объектно-ориентированным, объекты
должны удовлетворять некоторым
требованиям. Этими требованиями являются
инкапсуляциянаследование и полиморфизм.

Инкапсуляция —
Скрытие внутренней структуры объекта,что
позволяет сохранить методы и свойства
объекта при изменении способа
реализации(при копировании копируется
как одно целое,при удалении-удаляются
все его свойства и методы). В VB этот
принцип реализуется, в основном, за
счет применения описаний Private и Public.

Наследование —
Возможность создавать из существующих
классов, а на базе классов – объекты с
наследованием всех свойств и методов.

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

В
ООП центральным является
понятие классаКласс –
содержит описание можели объекта и
определяет выполненные действия, каждый
класс имеет набор свойств,методов и
связанных с ним собыий.

Объекты —
некоторая сущность реального мира. В
VBA
объекты – элементы пользовательского
интерфейса. С другой стороны,объект –
представитель некоторог класса
обнотипных объектов.

Создать
собственный класс в VB можно с помощью
модуля класса. Модуль
класса
 состоит
из элементов трех типов: свойствметодовсобытий,
оформляемых в виде описаний, процедур
и функций внутри контейнера — модуля.
У модуля класса нет собственного
пользовательского интерфейса — формы,
однако он может использовать контейнер
формы, для чего должен содержать
соответствующие методы.

Задача

Sub
Произвед_чётн_чисел() ’25 билет

Worksheets(1).Activate

Dim
i As Integer

Dim
pr As Integer

pr
= 1

For
i = 2 To 10 Step 2

pr
= pr * i

Next
i

Range(«E9»)
= «Произведение чётных чисел:»

Range(«H9»).Value
= pr

End
Sub

Билет
№26

1.Формы
представления моделей. Формализация.

1.модели
предметные
-воспроизводят
геометрич, физ. св-ва объектов в
материальной форме.(глобус, муляжи)

2.Информационны
модели
-объекты
и процессы в образной или знаковой
форме. обр. м.-зрительные образы
объектов(карты, картины); знаковые-строятся
с использ. различных языков(ноты,
таблицы).

Естественные
языки

использ. для создания описательных
информационных моделей.(гелиоцентрическая
модель мира Коперника)

Формальные
яз

– с помощью строятся формальные инфом.
модели(матем.)

Язык
алгебры

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

Язык
аглебры
логики
(алг.высказываний)
позв. строить формальные логические
модели.

Формализация-процесс
построения информационных моделей с
помощью формальных языков.

2.Понятие
алгоритма. Свойства алгоритмов.

Алгоритм-
точное предписание,которое определяет
процесс,ведущий от начальных данных к
требуемому конечному результату.

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

Свойства
алгоритма:

Результативность-возможность
получения результата после выполнения
конечного количества операций.

Определенность
– совпадение конечных результатов
независимо от пользователя и применяемых
средств.

Массовость
– возможно применение алгоритма к
целому классу однотипных задач

Способы
описания алгоритмов. Условные обозначения
блоков схем алгоритмов.

Для
алгоритма
необходимо описать его элементы:

Набор
объектов,составляющих совокупность
возможных исходных и конечных
данных,промежуточных результатов.

Правило
начала

Правило
непосредственной переработки информации

Правило
окончания

Правило
извлечения результатов

Способы
описания алгоритмов
:

Наиболее
популярные

Словесно-формульный
(в виде текста с формулами по
пунктам,определяющим последовательность
действий

Структурный/блок-схемный(геометрическими
фигурами,связанными линиями со стрелками)

С
помощью графических схем

С
помощью сетей Петри

Схема-единое
целое.

Блок-схема
должна содержать все разветвления,циклы
и обращения к подпрограммам,созданным
в программе.

Условные
обозначения.

Задача

Sub
Формула4()
’26 билет

Worksheets(1).Activate

Dim
a As String

a
= InputBox(«введите
число»)

Range(«A1»).Value
= a

If
Range(«A1»).Value > 15 Then

Range(«B1»).Value
= «БОЛЬШЕ»

Else

If
Range(«A1»).Value < 15 Then

Range(«B1»).Value
= «МЕНЬШЕ»

End
If

End
If

End
Sub

Билет
№27

1.Визуализация
формальных моделей

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

Описательные
инф. модели отображают объекты и явления
качественно, т.е. не используя количеств.
характеристик.

2.Редактор
Visual
Basic.
Проекта
VBA
и его структура

Приложения
в VBAсоздаются
посредством Visual
Basic.
Сервис/Макрос/Редактор ВБ

Основные
элементы главного окна редактора:

Окно
проекта

Окно
программного кода

Окно
просмотра

Окно
проекта (
Project)
VBA
и его структура

– часть приложения,позволяющая управлять
его элементами.View/Project
Explorer

Проект
рабочей книги включает в себя:

Объекты
Excel
– существующие рабочие листы и сама
книга

Формы
– пользовательские формы и модули
форм, содержащие коды процедур
обработки,событий формы и её элементов

Модули
– содержат макросы, пользовательские
процедуры и функции

Модули
класса

– программные коды класса.

В
проекте можно выделить визуальную
и программную
часть.
Прогрмаммная
часть хранится в модулях.

Добавление
модулей:

Insert
Module;

При
создании макроса или программного кода
– автоматически

Окно
программного кода – для
воода,просмотра,редактирование процедур
модуля. Для
открытия команды:

View/code

Двойной
щелчок на ___модуля

Билет
№28

1.
Т
ипы
информационных моделей.

1.
Табличные

– перечень однотипных объектов или
св-в размещён в первом столбце(строке)
таблицы, а значения – в ячейках.

2.Иерархичнские.
Класс
объектов-объекты с одинак.
св-вами=>подклассы.=>классификация.
В иерарх. инф.модели объекты распределены
по уровням.

2.1.статистическая
иер. моделькомпьютеры:сервреры,
суперкомпьютеры, персональные(портативные,
настольные, карманные).

Граф
– способ наглядного представления
структуры инф. моделей. вершина графа-овал
– отражают элементы системы.

2.2.динамическая
иерархич. модель – например генеалогическое
дерево.

3.Сетевые.
– применя.тся для отражения систем со
сложной структурой, в кот. связи м/у
элементами имеют произвольный характер.
Напр-Интернет.

2.Понятие
алгоритма. Свойства алгоритмов.

Алгоритм-
точное предписание,которое определяет
процесс,ведущий от начальных данных к
требуемому конечному результату.

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

Свойства
алгоритма:

Результативность-возможность
получения результата после выполнения
конечного количества операций.

Определенность
– совпадение конечных результатов
независимо от пользователя и применяемых
средств.

Массовость
– возможно применение алгоритма к
целому классу однотипных задач

Способы
описания алгоритмов. Условные обозначения
блоков схем алгоритмов.

Для
алгоритма
необходимо описать его элементы:

Набор
объектов,составляющих совокупность
возможных исходных и конечных
данных,промежуточных результатов.

Правило
начала

Правило
непосредственной переработки информации

Правило
окончания

Правило
извлечения результатов

Способы
описания алгоритмов
:

Наиболее
популярные

Словесно-формульный
(в виде текста с формулами по
пунктам,определяющим последовательность
действий

Структурный/блок-схемный(геометрическими
фигурами,связанными линиями со стрелками)

С
помощью графических схем

С
помощью сетей Петри

Билет
№29

1..Основные
этапы разработки и исследования моделей
на компьютере.

Информационное
моделирование-творческий процесс.

Этапы:

1.Описательная
информационная модель-зад. сущ. праметры
объекта.

2.Формализованная
модель-описательная информация
записывается с помощью формального
языка.

3.
Компьютерная модель.-преобразование
формл.модели в компьютерную-создание
с использованием электронных таблиц
или других приложений или в форме
проекта на одном из языком программирования.

4.Компьютерный
эксперимент.

5.Анализ
полученных результатов и корректировка
исследуемой модели

2.Типы
данных. Объявление переменных.

В
VBA
все данные:

Числа

Текст

Даты

Лигоческие

И
тд

Integer
– числовые данные(целые -32768 до +32768)

Currency
– числа с 4 знаками после запятой

String
– текстовые деанные,в кавычках.

Double
– дробные

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

Переменную
можно объявить явно или неявно (в
небольших программах можно не объявлять).

Dim
ИмяПеременной
as
[Тип]

задача

Sub
Сумма_чётн() ’29 билет

Worksheets(1).Activate

s
= 0

For
i = 18 To 36 Step 2

s
= s + i

Next
i

Range(«E9»)
= «Сумма
чётных
чисел:»

Range(«H9»)
= s

End
Sub

50

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #

Понравилась статья? Поделить с друзьями:
  • Относительная ссылка в формуле ms excel изменится если формулу
  • Относительную ссылку макрос excel
  • Относительная ссылка в формулах в ms excel это
  • Относительной ссылкой в ms excel называется
  • Относительная ссылка в excel это формула