Vba excel ссылка на ячейку в другой книге

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

Ссылки на другую книгу

В ячейку «A1» листа «Лист6» текущей книги вставлена ссылка на ячейку «C12» листа «Лист1» книги «Другая книга.xlsm».

Ссылка в ячейке, если книга «Другая книга.xlsm» открыта:

=‘[Другая книга.xlsm]Лист1’!$C$12

Ссылка в ячейке, если книга «Другая книга.xlsm» закрыта:

=‘C:UsersEvgeniyDesktop[Другая книга.xlsm]Лист1’!$C$12

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

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

Обращение к ячейке по ссылке

Обращение из кода VBA Excel к ячейке в другой книге для определения ее координат по ссылке из ячейки «Лист6!A1» текущей книги:

MsgBox Range(ThisWorkbook.Sheets(«Лист6»).Range(«A1»).Formula).Row  ‘Результат = 12

MsgBox Range(ThisWorkbook.Sheets(«Лист6»).Range(«A1»).Formula).Column  ‘Результат = 3

Примеры обращения к другой книге

Условие

В ячейке «A1» листа «Лист6» текущей книги размещена ссылка: ='[Другая книга.xlsm]Лист1'!$C$12. Необходимо перейти по ссылке из ячейки «Лист6!A1» в другую книгу, скопировать диапазон из 9 ячеек (3х3) в другой книге, где первой ячейкой диапазона является ячейка из ссылки, и вставить скопированный диапазон в диапазон «Лист6!A2:C4» текущей книги.

Решение

Если точно известно, что другая книга открыта:

Sub Primer1()

    With ThisWorkbook.Sheets(«Лист6»)

        Range(.Range(«A1»).Formula).Resize(3, 3).Copy .Range(«A2:C4»)

    End With

End Sub

Если неизвестно, открыта другая книга или нет:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

‘Функция для проверки состояния книги (открыта или нет)

Function BookOpenClosed(wbName As String) As Boolean

    Dim myBook As Workbook

    On Error Resume Next

        Set myBook = Workbooks(wbName)

    BookOpenClosed = Not myBook Is Nothing

End Function

Sub Primer2()

Dim s1 As String, s2 As String, s3 As String, n1 As Long, n2 As Long

    ‘записываем ссылку из ячейки Лист6!A1 в переменную s1

    s1 = ThisWorkbook.Sheets(«Лист6»).Range(«A1»).Formula

    ‘вырезаем имя книги из ссылки и записываем в переменную s2

    n1 = InStr(s1, «[«)

    n2 = InStr(s1, «]»)

    s2 = Mid(s1, n1 + 1, n2 n1 1)

        ‘проверяем состояние книги

        If Not BookOpenClosed(s2) Then

            ‘если книга закрыта, вырезаем путь к ней из ссылки и записываем в переменную s3

            n1 = InStr(s1, «:») — 1

            n2 = InStrRev(s1, ««)

            s3 = Mid(s1, n1, n2 n1 + 1)

            ‘открываем другую книгу, объединив путь к ней и ее имя

            Workbooks.Open (s3 & s2)

        End If

    ‘копируем ячейки из другой книги в текущую

    Range(s1).Resize(3, 3).Copy ThisWorkbook.Sheets(«Лист6»).Range(«A2:C4»)

End Sub

И еще один вариант кода VBA Excel для случаев, когда неизвестно, открыта книга или нет. Здесь просто осуществляется попытка открыть книгу, и она будет открыта, если в ячейке содержится ее полное имя, включая диск и подкаталоги. В случае возникновения ошибки, управление будет передано следующей строке.

Sub Primer3()

Dim s1 As String, s2 As String, n1 As Long, n2 As Long

    ‘записываем ссылку из ячейки Лист6!A1 в переменную s1

    s1 = ThisWorkbook.Sheets(«Лист6»).Range(«A1»).Formula

    ‘вырезаем полное имя книги из ссылки и записываем в переменную s2

    On Error Resume Next

    n1 = InStr(s1, «:») — 1

    n2 = InStrRev(s1, «]«)

    s2 = Mid(s1, n1, n2 — n1)

    s2 = Replace(s2, «[«, ««)

    ‘пробуем открыть книгу, если она не открыта

    Workbooks.Open (s2)

    On Error GoTo 0

    ‘копируем ячейки из другой книги в текущую

    Range(s1).Resize(3, 3).Copy ThisWorkbook.Sheets(«Лист6«).Range(«A2:C4«)

End Sub

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


 

Вася Вася

Пользователь

Сообщений: 15
Регистрация: 24.12.2012

Добрый день.
В книге FD00148.xlsx на листе Report есть нужная мне ячейка L29. Я хочу вручную проложить путь к этому файлу и получить из него значение в ячейке L29, чтобы при перемещении на другой комп ссылка на устарела.
Путь к файлу через PLEX я нашел, а вот как сослаться на конкретную ячейку на конкретном листе, имея в формате текста путь к файлу, я не знаю. Помогите.
Хочу найти что-то наподобие такого:
=ПОЛУЧИТЬЗНАЧЕНИЕ(‘C:Documents and Settingscounter-filРабочий столDesktopМои документыАнализ проектовFD2Q 2012[FD00148.xlsx]Report’!$L$29),
т.е. склеиваешь полностью ссылку на ячейку и получаешь значение этой ячейки в заданной книге.

ПС. Сори админы, примера приложить не могу, всё в тексте.

Изменено: Вася Вася30.03.2016 02:54:59

 

Z

Пользователь

Сообщений: 6111
Регистрация: 21.12.2012

Win 10, MSO 2013 SP1

А открыть в одном процессе обе книги, гляцнуть «=», перейти в другую и выбрать нужное — не пробовали?..

«Ctrl+S» — достойное завершение ваших гениальных мыслей!.. ;)

 

ikki

Пользователь

Сообщений: 9709
Регистрация: 22.12.2012

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

Вася Вася

Пользователь

Сообщений: 15
Регистрация: 24.12.2012

#4

24.12.2012 14:12:39

ikki, то что нужно. А можно ли это сделать как функцию (чтобы в ячейку можно было поставить =МояФункция(….)? В ней я нашел три аргумента — Путь к файлу, лист, ячейка (выделены красным)? Я не программист, вот в чем дело.

Код
Sub Get_Value_From_Close_Book()
 Dim sShName As String, sAddress As String, vData
 'Отключаем обновление экрана
 Application.ScreenUpdating = False
 Workbooks.Open [COLOR=#FF0000]"C:Documents and SettingsКнига1.xls"[/COLOR]
 sAddress = [COLOR=#FF0000]"A1:C100"[/COLOR] 'или одна ячейка - "A1"
 'получаем значение
 vData = Sheets([COLOR=#FF0000]"Лист1"[/COLOR]).Range(sAddress).Value
 ActiveWorkbook.Close False
 'Записываем данные на активный лист книги,
 'с которой запустили макрос
 If IsArray(vData) Then
 [A1].Resize(UBound(vData, 1), UBound(vData, 2)).Value = vData
 Else
 [A1] = vData
 End If
 'Включаем обновление экрана
 Application.ScreenUpdating = True
 

ikki

Пользователь

Сообщений: 9709
Регистрация: 22.12.2012

а у вас всего одна такая ячейка со ссылкой?
а то каждый раз открывать/закрывать файл при запуске функции — как-то не айс.

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

Вася Вася

Пользователь

Сообщений: 15
Регистрация: 24.12.2012

Не, у меня будет много на листе.

 

Вася Вася

Пользователь

Сообщений: 15
Регистрация: 24.12.2012

Ладно, всем спасибо, вопрос решен.
Я думал проще будет.

 

ikki

Пользователь

Сообщений: 9709
Регистрация: 22.12.2012

#8

24.12.2012 14:34:31

такая функция:

Код
Function Get_Value_From_Close_Book(wbName$, sheetName$, strAddress$)
  Dim sShName As String, sAddress As String, vData
  'Отключаем обновление экрана
  Application.ScreenUpdating = False
  Workbooks.Open wbName
  'получаем значение
  Get_Value_From_Close_Book = Sheets(sheetName).Range(strAddress).Value
  ActiveWorkbook.Close False
  Application.ScreenUpdating = True
End F unction

нерабочая.
файл не открывает, ошибку не выдает.
есть подозрение, что в UDF операция открытия файла не разрешена.

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#9

24.12.2012 14:41:28

Можно все.

Код
Function Get_Value_From_Close_Book(sWb As String, sShName As String, sAddress As String)
    Dim vData, objCloseBook As Object
    Set objCloseBook = GetObject(sWb)
    'получаем значение
    vData = objCloseBook.Sheets(sShName).Range(sAddress).Value
    objCloseBook.Close False
    'Возвращаем данные в ячейку с функцией
    If IsArray(vData) Then
        Get_Value_From_Close_Book = vData
    Else
        Get_Value_From_Close_Book = vData
    End If
End F unction

Чтобы получить массив ячеек, необходимо выделить несколько ячеек и ввести в них эту функцию, как формулу массива.
Вызов с листа:
=Get_Value_From_Close_Book(«C:Книга1.xls»;»Лист1″;»B1″)

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

ikki

Пользователь

Сообщений: 9709
Регистрация: 22.12.2012

The_Prist, понятно.
кстати, процедуру Get_Value_From_Close_Book_Excel4Macro() в виде функции тоже «перепилить» не удалось :(

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

Вася Вася

Пользователь

Сообщений: 15
Регистрация: 24.12.2012

 

Вася Вася

Пользователь

Сообщений: 15
Регистрация: 24.12.2012

The_Prist, Эх, ошибку выдает.

 

R Dmitry

Пользователь

Сообщений: 3103
Регистрация: 22.12.2012

Excel,MSSQL,Oracle,Qlik

#13

25.12.2012 13:38:01

Цитата
End F unction

Здесь пробел убрали? (форум подглючивает)
Правильно надо (End Function)

Спасибо

 

ikki

Пользователь

Сообщений: 9709
Регистрация: 22.12.2012

и квадратик перед Value — тоже :)

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

Вася Вася

Пользователь

Сообщений: 15
Регистрация: 24.12.2012

Убрал конечно.
Ошибку функция выдает после того, как вводишь её =Get_Value… в ячейку и жмешь Enter. Функция берет нужное значение из закрытой книги, но потом Excel виснет.

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Эх, а у меня не выдает….книга-то где находится? Параметры какие в функцию передаете? Что еще на листе есть?

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Вася Вася

Пользователь

Сообщений: 15
Регистрация: 24.12.2012

The_Prist, сори, сил нет чтобы оттестировать ещё раз. На пустой книге попробовал — работает. После НГ уже займусь.
Большое спасибо.

 

zOn

Пользователь

Сообщений: 13
Регистрация: 29.03.2016

#18

29.03.2016 22:02:44

Цитата
The_Prist написал:
   If IsArray(vData) Then        Get_Value_From_Close_Book = vData    Else        Get_Value_From_Close_Book = vData    End If

может ошибка возникает из-за того, что и Then и Else выполняют одно и тоже?

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#19

30.03.2016 00:47:23

Не думаю, что Вася Вася столько времени ждёт ответ — с 30 декабря 2012 года ))  


Форум программистов Vingrad

Новости ·
Фриланс ·
FAQ

Правила ·
Помощь ·
Рейтинг ·
Избранное ·
Поиск ·
Участники

Форум -> Компьютерные системы -> MS Office, Open Office и др. -> Программирование, связанное с MS Office
(еще)

Модераторы: mihanik

Поиск:

Ответ в темуСоздание новой темы
Создание опроса
> Как сделать ссылку на ячейку в другой книге? VBA 

:(

   

Опции темы

transkriptsiya
Дата 21.12.2012, 16:47 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Шустрый
*

Профиль
Группа: Участник
Сообщений: 101
Регистрация: 17.1.2008

Репутация: нет
Всего: нет

Private Sub CheckBox18_Click()
If CheckBox18 Then
Range(«A9») = 1
Else: Range(«A9») = Worksheets(«Лист2»).Range(«A1»)
End If
End Sub

так беру значение Range(«A1») с другого листа, а как взять с другой книги . (одна лежит в той-же директории, другая- в другом месте)?

PM MAIL   Вверх
Akina
Дата 21.12.2012, 17:12 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Советчик
****

Профиль
Группа: Модератор
Сообщений: 20560
Регистрация: 8.4.2004
Где: Зеленоград

Репутация: 25
Всего: 453

Цитата(transkriptsiya @  21.12.2012,  17:47 Найти цитируемый пост)
как взять с другой книги 

Открыть, затем сослаться

Код

Workbooks("Книга2").Worksheets("Лист2").Range("A1")

———————

 О(б)суждение моих действий — в соответствующей теме, пожалуйста. Или в РМ. И высшая инстанция — Администрация форума.

PM MAIL WWW ICQ Jabber   Вверх



















Ответ в темуСоздание новой темы
Создание опроса
Правила форума «Программирование, связанное с MS Office»

mihanik

staruha

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми
компонентами


  • Несанкционированная реклама на форуме запрещена
  • Пожалуйста, давайте своим темам осмысленный, информативный заголовок. Вопль «Помогите!» таковым не является.
  • Чем полнее и яснее Вы изложите проблему, тем быстрее мы её решим.
  • Оставляйте свои записи в

    «Книге отзывов о работе администрации»

  • А вот тут лежит FAQ нашего подраздела


Если Вам понравилась атмосфера форума, заходите к нам чаще!

С уважением
mihanik и
staruha.

 

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Программирование, связанное с MS Office | Следующая тема »

Подписаться на тему |
Подписка на этот форум |
Скачать/Распечатать тему

[ Время генерации скрипта: 0.0951 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]

Реклама на сайте
   
Информационное спонсорство

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

Всем привет.
Есть две книги, условно назовем их Source.xlsx и Another.xlsx
Source.xlsx может находиться где угодно. Another.xlsx находится, например, C:UsersUserDesktop
В Source.xlsx, после изменения активной ячейки, происходит ее обработка макросом, а именно нужно добавить гиперссылку на определенную ячейку («B5»), определенного листа («Main») книги Another.xlsx, которая находится по вышеуказанному пути. И соответственно, при нажатии на эту гиперссылку, открыть книгу с фокусом на указанную в гиперссылке ячейку.
Пока что у меня примерно так, но код не работает.

Visual Basic
1
2
3
4
5
6
    If TypeOf Selection Is Range Then
        ThisWorkbook.ActiveSheet.Hyperlinks.Add Anchor:=Selection, _
        Address:="", _
        SubAddress:="'C:UsersUserDesktop[Another.xlsx]Main'!$B$5", _
        ScreenTip:="'C:UsersUserDesktop[Another.xlsx]Main'!$B$5"
    End If

Добавлено через 49 минут
Нашел решение следующим образом:

Visual Basic
1
2
3
4
5
6
    If TypeOf Selection Is Range Then
        ThisWorkbook.ActiveSheet.Hyperlinks.Add Anchor:=Selection, _
        Address:="C:UsersUserDesktopAnother.xlsx", _
        SubAddress:="'Main'!$B$5", _
        ScreenTip:="C:UsersUserDesktopAnother.xlsx'Main'!$B$5"
    End If

In this guide, we’re going to show you how to refer a range or a cell in Excel VBA.

VBA Basics

Before diving into the code, let’s start with a cell or a range means in VBA. First, VBA is an object-based programming language, which means that the language refers each element as objects. Objects have properties that define them, and they can encapsulate other objects, or codes. Thus, a single cell, a range of cells, a worksheet, or Excel software as a whole is an object for VBA. You can think this as a hierarchical model.

The image illustrates only a small portion of Excel objects in VBA. An Excel instance contains a Workbooks collection. A collection is a group of related objects. For example, if you open two workbooks, the Workbooks collection has two Workbook object. Each Workbook object has its own worksheets under a Worksheets collection. This structure applies to all.

VBA envelops all cell and cell-based references in an object called Range. In theory, when a particular object is referenced, you also need to specify its parents. In VBA syntax, a dot (.) operator is used to move through object hierarchy. For example, to access the Range object, the code should be:

Application.Workbooks.Worksheets.Range

However, this reference is ambiguous when it comes to specify which Excel workbook or worksheet you are referring to. In order to do this, you must supply the name or the index number (starting with 1) of the particular object you are referring. This approach is like in Excel formulas — the argument is given in parentheses. For example to refer the range object in the worksheet “Sheet1” of the workbook “Book1.xlsm”:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range

or

Application.Workbooks(1).Worksheets(1).Range

You do not have to specify all parents for Range object every time. If your intention is to work on the active sheet of the active workbook, you can simply use Range.

Range Object

The Range object allows you to refer a cell or cells just like in any Excel formula. For example,

Range("A1") 'Refers the cell A1
Range("A2:D11") 'Refers the range of cells between A2:D11
Range("A3,B4:E6,F12") 'Refers all cells in the cells A3, F12 and the range B4:E6
Range("2:2") 'Entire 2nd row
Range("E:E") 'Entire column E
Range("Input") 'Named range "Input"

Using square brackets to refer a range or a cell

You can use square brackets ([]) instead of the “Range” keyword and double quotes (“). This approach as essentially a shortcut, and the outcome is the same.

[A1] 'Refers the cell A1
[A2:D11] 'Refers the range of cells between A2:D11
[A3,B4:E6,F12] 'Refers all cells in the cells A3, F12 and the range B4:E6
[2:2] 'Entire 2nd row
[E:E] 'Entire column E
[Input] 'Named range "Input"

Cells property to refer a range or a cell

Cells is the name of a property of both Worksheet and Range objects. It is neither a collection nor an object. Thus, there are no objects named Cell.

In other words, the Cells property returns a Range object as well. Each Cells property in Worksheet and Range objects work in its parent’s context only. This behavior might make more sense within examples.

Syntax

The Cells property can be used in two ways:
With row and column index numbers:

Cells(row number,column number) 

With index number of the cell:

Cells(cell number) ‘refers the 23rd cell in the range

Examples

Worksheet.Cells

Cells property of a Worksheet object returns the cell in a specific location in the worksheet.
With row and column index numbers:

Cells(3,2) 'refers the cell at third row and second column in the active sheet (B3)

How to refer a range or a cell in Excel VBA 02
With index number of the cell:

Cells(5) 'refers the 5th cell in the range (E1)

The numbering of cells starts from 1, and increases from left to right and from top to bottom. This means that A1 is the first cell.

Range.Cells

On the other hand, the Cells property of a Range object returns the cell in specified location in the range.
With row and column index numbers:

Range("C4:F9").Cells(3,2) 'refers the cell at third row and second column in the active range (D6)


With index number of the cell:

Range("C4:F9").Cells(5) ‘refers the 5th cell in the range (C5)

Active objects to refer a range or a cell

There are keywords in VBA to reference active(selected) objects when the code is running.

ActiveCell 'Refers the selected cell
Selection 'Refers any selected object. This can be cells or a chart
ActiveSheet 'Refers the active worksheet
ActiveWorkbook 'Refers the active worksheet

Performing actions with macros in VBA

What are VBA Cell References?

After creating the macro and declaring the variables, the next step is to create VBA cell references, which actually refer to each variable and can then be used to manipulate the data within the Excel sheet. Performing actions on variables for data reference are known as VBA methods.

To do this, you need to know the different methods you can apply within VBA. The ideal first step is to learn how to refer to specific data cells.

learn about VBA cell references

Learn more in CFI’s VBA Modeling Course.

VBA Cell References – Referencing Files and Worksheets

To know which data it needs to manipulate, you need to tell Excel where to find the data. This is done in the following hierarchy: Workbook (Excel File) > Worksheet > Range or Cell. If you skip levels of the hierarchy, Excel will simply assume that it should look in the currently active Workbook or Worksheet. You cannot skip the last level. You need to tell Excel a specific range or cell or tell Excel to look in the active cell. Telling Excel which workbook and worksheet to look under is not necessary, but is valuable when multiple workbooks and worksheets are open.

  • To refer to a workbook: Workbooks(“NameOfFile.xls”).
  • Use the specific name of the file, followed by the extension.
  • To refer to the current workbook, the macro is located in: ThisWorkbook
  • To refer to the active workbook: ActiveWorkbook
  • To refer to a worksheet: Worksheets(“Sheet1”) or Sheets(“Sheet1”)
  • Use the name of the sheet.
  • To refer to the active worksheet: ActiveWorksheet

VBA Cell References – Selecting Ranges or Cells

Selecting ranges and cells works a bit differently compared to selecting books and sheets. You can select one or more cells (known as a range) or even multiple ranges. Looking at the code, you may be familiar with it, as the text enclosed in the parenthesis is similar to that used in Excel formulas.

  • Selecting one cell: Range(“B5”)
  • Selecting one range: Range(“B5:D5”)
  • Selecting multiple ranges and cells: Range(“B5:D5,E10:J50,M99”)
  • Selecting the active cell (whatever is currently selected in the Excel file): ActiveCell
  • Selecting the active selection (multiple active cells): Selection
  • Selecting all cells within a current worksheet: Cells

VBA Cell References – Putting it All Together

Now that you know how to refer to books, sheets, and cells, you need to combine these into one line, separated by a period symbol. For example, to select range A42 to D45 in sheet3 of the currently active workbook:

ActiveWorkbook.Sheets(“sheet3”).Range(“A42:D45”)

This is the VBA cell reference that Excel needs to find the data you want to work with. However, now you need to tell Excel what to do with the data. This is where you start working with methods.

Manipulating VBA Cell References

From here, it gets a little complicated. Each reference has many different actions (known as “methods”) that it can take, and certain references have methods that are unavailable to others. However, to keep things simple, let’s discuss how to tell Excel to select and highlight the data in the model, how to copy it, and how to store it.

To highlight the data in the model, the proper method to use is “Select” or “Activate”.

ActiveWorkbook.Sheets(“sheet3”).Range(“A42:D45”).Select

ActiveWorkbook.Sheets(“sheet3”).Range(“A42:D45”).Activate

Running this macro by pressing F5 will cause Excel to highlight the range A42 to D45.

To copy the data in the model, the method to use is “Copy.”

ActiveWorkbook.Sheets(“sheet3”).Range(“A42:D45”).Copy

Running this macro will tell Excel to copy the contents of the range to be pasted later. If you run this macro, you’ll notice that Excel will highlight the range with the “running ants” that you normally see when you copy data.

To access the value in a cell, you use the “Value” method. Using value, you can store the value in a cell within a variable, or copy the exact value of that cell into another cell. Note that the value command does not work with ranges. It will only work with singular cells.

Range(“A45”).Value = Range(“A42”).Value

Macros will always read from left to right. This means that Cell A45 will now contain the value within Cell A42 after the macro is run.

To store the value of a cell in a variable, you use the “Value” method, but you must also tell Excel which variable to store it under. This action won’t work for a range, as Excel can only store one piece of data within each Variable.

Dim myVariable as String

myVariable = ActiveWorkbook.Sheets(“sheet3”).Range(“A42”).Value

If, for example, range A42 contained the phrase “Corporate Finance Institute”, it would be now stored under the myVariable string variable. You can use this method to store values for later use. This action is also useful when you need to use the same piece of data multiple times, so you don’t have to type the long reference each time. Instead of typing the workbook, sheet, and range, you can simply use the variable you stored it under.

Additional Resources

Thank you for reading CFI’s guide on VBA Cell References. To keep learning and developing your knowledge base, please explore the additional relevant resources below:

  • VBA Do Loop
  • VBA For Loop
  • Excel Shortcuts
  • VBA Financial Modeling Course
  • See all Excel resources

Понравилась статья? Поделить с друзьями:
  • Vba excel ссылка на эту книгу
  • Vba excel ссылка на форму
  • Vba excel ссылка на текущий лист
  • Vba excel ссылка на таблицу
  • Vba excel ссылка на столбец