Vba excel type in cell

If you actually want the cell type to be specified, you can’t. All cells in VBA contain variant data types, to the best of my knowledge.

If you mean the data type of the variant, then sure, you can do it one way or another. Here’s a suggestion, it’s a little quick and dirty but it works. You’ll need to put it in your worksheet code module. Note that it doesn’t test if your bool range, int range, whatever intersect, that could cause you some problems if they do.

Private Sub Worksheet_Change(ByVal Target As Range)

    On Error GoTo handler

    Dim cell As Range, _
        boolRng As Range, _
        intRng As Range

    Set boolRng = Union(Sheet1.Range("A1:B2"), Sheet1.Range("E:E"))
    Set intRng = Union(Sheet1.Range("B7:K12"), Sheet1.Range("M:M"))

    If Not Intersect(Target, boolRng) Is Nothing Then
        For Each cell In Intersect(Target, boolRng)
            If cell.Value <> "" Then
                cell.Value = CBool(cell.Value)
            End If
        Next cell
    End If

    If Not Intersect(Target, intRng) Is Nothing Then
        For Each cell In Intersect(Target, intRng)
            If cell.Value <> "" Then
                cell.Value = CInt(cell.Value)
            End If
        Next cell
    End If

    Exit Sub

handler:
    Select Case Err.Number
        Case 13 'Type mismatch, raised when cint/cbool/c*** fails
            cell.Value = ""
            Resume Next
        Case Else
            Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
    End Select

End Sub

Edit: I note you want to raise an error if the value is assigned incorrectly, you can do that in the error handling section. Instead of

Cell.value = ""
Resume Next

You could use

Err.Raise ISuggestAnEnumForErrorNumbers, "Sheet1.Worksheet_Change(Event)", "Attempted to assign wrong type to cell."

Return to VBA Code Examples

This article will demonstrate the use of the VBA TypeName Function.

The VBA TypeName Function is used in determining the type of data stored in a cell, or the type of a selected object – for example a worksheet, range or cell, or a control on a form.

Determining the Data Type in a Cell

To determine was datatype in in a cell we can use the TypeName function with the Cells Property.

Sub TestCellDataType()
  MsgBox "The type of data in " & Cells(3, 2).Address & " is " & TypeName(Cells(3, 2).Value)
End Sub

If we run this code above with the worksheet below, the message box will tell us what type of data is in the cell.

VBA Text TypeName Double

Determining the type of Object Selected

We can also use TypeName to determine what type of Object has been selected in a worksheet – a Range or a Chart for example.

Sub TestSelection()
  MsgBox "You have selected a " & TypeName(Selection)
End Sub

VBA Text TypeName Range

Or, if we select a chart:

We can drill down even further and select the objects within the chart, and the macro will return what we have selected.

VBA Text TypeName Series

All of this can be most useful in building our VBA project to either control the flow of the code, or to prevent errors from occurring by testing to ensure the correct type of object is selected, or the correct type of data is entered into a cell.

Using TypeName on Form Controls

VBA enables us to create interactive forms that the user can fill in and return data to the code to be used in various ways.  We can use the TypeName operator to determine the type of controls that are being used on a form.

In the example below, I have created a user form with a variety of controls on it – a couple of Text Boxes, a Combo Box, 2 option buttons, 2 check boxes and 3 command buttons.

VBA Text TypeOf Form Intro

Using the code below, I can determine what type of controls are on the form by looping through all the controls on the form. I have used the TypeName function to return a message with the type of the control with a VBA IF Statement to check what type of control is selected.

Sub WhatControlType()
  Dim ctl As Object
  For Each ctl In Me.Controls
     MsgBox "The control is a " & TypeName(ctl)
  Next ctl
End Sub

This type of code can be very useful if we wish to enable or disable controls. In the code below, when the form is first opened, the option buttons and check boxes are disabled.

Private Sub UserForm_Initialize()
  Dim ctl As Object
  For Each ctl In Me.Controls
     If TypeName(ctl) = "CheckBox" Then
       ctl.Enabled = False
     ElseIf TypeName(ctl) = "OptionButton" Then
       ctl.Enabled = False
    Else
       ctl.Enabled = True
    End If
  Next ctl
End Sub


VBA Text TypeOf_Form

To enable the option buttons and checkboxes, I have written some further code behind the Enable Controls button.

Private Sub cmdEnable_Click()
  Dim ctl As Object
  For Each ctl In Me.Controls
     If TypeName(ctl) = "CheckBox" Then
        ctl.Enabled = Not ctl.Enabled
     ElseIf TypeName(ctl) = "OptionButton" Then
        ctl.Enabled = Not ctl.Enabled
     End If
  Next ctl
End Sub

The functionality in this code can also be created using the VBA TypeOf Operator.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

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

Чтобы определить какой тип данных в ячейке или в переменной типа Variant, можно воспользоваться несколькими способами.

Способ 1. Использовать функцию TypeName для определения типа данных

Эта функция возвращает строку с названием типа данных на английском. В качестве аргумента принимает переменную, значение ячейки.
Обратите внимание: Функция определяет только стандартные типы данных и не может определить пользовательский тип (определенный с помощью Type).

Возможные возвращаемые функцией значения:

Byte Число типа Byte
Integer Целое число
Long Длинное целое число
Single Число одиночной точности с плавающей запятой
Double Число двойной точности с плавающей запятой
Currency Валюта
Decimal Число с плавающей запятой
Date Дата
String Строка
Boolean Логическое
Error Ошибка
Empty Не проинициализировано (т.е. переменная не была объявлена)
Null Неверные данные (в переменной нет корректных данных)
Object Объект (класс)
Unknown Тип данных не известен
Nothing Объект, никуда не ссылающийся

Приведу несколько примеров по использованию TypeName.

Пример 1. Определение типа переменной.

Dim v As Integer
MsgBox TypeName(v) ' Выведет: Integer

Обратите внимание: если вы используете результат TypeName в условии, т.е. проверяете, соответствует ли тип данных определенному, например, Integer, то регистр символов возвращаемого типа имеет значение. Т.е. нужно писать Integer с заглавной буквы, либо использовать приведение всех символов к одному регистру.

Пример 2. Использование TypeName в условии.

Dim v As Integer
If TypeName(v) = "Integer" Then MsgBox "Yes" Else MsgBox "No"         ' Yes
If TypeName(v) = "integer" Then MsgBox "Yes" Else MsgBox "No"         ' No
If LCase(TypeName(v)) = "integer" Then MsgBox "Yes" Else MsgBox "No"  ' Yes

Пример 3. Определение типа данных в ячейке.

MsgBox TypeName(Cells(1, 1).Value) ' Выведет тип данных в ячейке A1

Если функции была передана переменная массив, она вернет тип данных в массиве с добавлением скобок.

Пример 4. Определение типа массива.

Dim Arr1(10) As Integer
Dim Arr2(10)
MsgBox TypeName(Arr1) ' Выведет: Integer()
MsgBox TypeName(Arr2) ' Выведет: Variant()

Способ 2. Проверка на возможность преобразования строки к нужному типу.

Бывает ситуация, когда значение, например, число или дата, содержится в строке. В этом случае TypeName вернет String, а не Integer или Date. Чтобы узнать, что содержится в строке, можно воспользоваться одной из функций IsNumeric, IsDate, IsObject, IsArray, IsNull, IsError.

IsNumeric Проверяет может ли выражение быть преобразовано в число
IsDate Проверяет может ли выражение быть преобразовано в дату
IsObject Проверяет, является ли переменная объектом
IsArray Проверяет, является ли переменная массивом
IsNull Проверка на пустое значение
IsError Проверка выражения на ошибку

Пример 4. Определение может ли переменная быть преобразована в число.

Dim v As String
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no (т.к. в строке нет числа)
v = "120"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
v = "120.45"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no
v = "test 120"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no
v = "120 test"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no

К сожалению, как видим из примера, нет возможности проверить, содержится ли в строке число с плавающей точкой.

Пример 5. Определение содержит ли переменная дату (может быть преобразована в дату).

Dim firstDate, secondDate As Date
Dim timeOnly, dateAndTime, noDate As String
firstDate = CDate("12.05.2017")
secondDate = #12/5/2017#
timeOnly = "15:45"
dateAndTime = "12.05.2017 15:45"
noDate = "Test"
If IsDate(firstDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(secondDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(timeOnly) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(dateAndTime) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(noDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no

Проверка, содержится ли число или дата в ячейке листа делается аналогично, как и с переменными.

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

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

Объект Range в VBA Excel представляет диапазон ячеек. Он (объект Range) может описывать любой диапазон, начиная от одной ячейки и заканчивая сразу всеми ячейками рабочего листа.

Примеры диапазонов:

  • Одна ячейка – Range("A1").
  • Девять ячеек – Range("A1:С3").
  • Весь рабочий лист в Excel 2016 – Range("1:1048576").

Для справки: выражение Range("1:1048576") описывает диапазон с 1 по 1048576 строку, где число 1048576 – это номер последней строки на рабочем листе Excel 2016.

В VBA Excel есть свойство Cells объекта Range, которое позволяет обратиться к одной ячейке в указанном диапазоне (возвращает объект Range в виде одной ячейки). Если в коде используется свойство Cells без указания диапазона, значит оно относится ко всему диапазону активного рабочего листа.

Примеры обращения к одной ячейке:

  • Cells(1000), где 1000 – порядковый номер ячейки на рабочем листе, возвращает ячейку «ALL1».
  • Cells(50, 20), где 50 – номер строки рабочего листа, а 20 – номер столбца, возвращает ячейку «T50».
  • Range("A1:C3").Cells(6), где «A1:C3» – заданный диапазон, а 6 – порядковый номер ячейки в этом диапазоне, возвращает ячейку «C2».

Для справки: порядковый номер ячейки в диапазоне считается построчно слева направо с перемещением к следующей строке сверху вниз.

Подробнее о том, как обратиться к ячейке, смотрите в статье: Ячейки (обращение, запись, чтение, очистка).

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

Еще надо добавить, что свойства и методы объектов отделяются от объектов точкой, как в третьем примере обращения к одной ячейке: Range("A1:C3").Cells(6).

Свойства ячейки (объекта Range)

Свойство Описание
Address Возвращает адрес ячейки (диапазона).
Borders Возвращает коллекцию Borders, представляющую границы ячейки (диапазона). Подробнее…
Cells Возвращает объект Range, представляющий коллекцию всех ячеек заданного диапазона. Указав номер строки и номер столбца или порядковый номер ячейки в диапазоне, мы получаем конкретную ячейку. Подробнее…
Characters Возвращает подстроку в размере указанного количества символов из текста, содержащегося в ячейке. Подробнее…
Column Возвращает номер столбца ячейки (первого столбца диапазона). Подробнее…
ColumnWidth Возвращает или задает ширину ячейки в пунктах (ширину всех столбцов в указанном диапазоне).
Comment Возвращает комментарий, связанный с ячейкой (с левой верхней ячейкой диапазона).
CurrentRegion Возвращает прямоугольный диапазон, ограниченный пустыми строками и столбцами. Очень полезное свойство для возвращения рабочей таблицы, а также определения номера последней заполненной строки.
EntireColumn Возвращает весь столбец (столбцы), в котором содержится ячейка (диапазон). Диапазон может содержаться и в одном столбце, например, Range("A1:A20").
EntireRow Возвращает всю строку (строки), в которой содержится ячейка (диапазон). Диапазон может содержаться и в одной строке, например, Range("A2:H2").
Font Возвращает объект Font, представляющий шрифт указанного объекта. Подробнее о цвете шрифта…
HorizontalAlignment Возвращает или задает значение горизонтального выравнивания содержимого ячейки (диапазона). Подробнее…
Interior Возвращает объект Interior, представляющий внутреннюю область ячейки (диапазона). Применяется, главным образом, для возвращения или назначения цвета заливки (фона) ячейки (диапазона). Подробнее…
Name Возвращает или задает имя ячейки (диапазона).
NumberFormat Возвращает или задает код числового формата для ячейки (диапазона). Примеры кодов числовых форматов можно посмотреть, открыв для любой ячейки на рабочем листе Excel диалоговое окно «Формат ячеек», на вкладке «(все форматы)». Свойство NumberFormat диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковый числовой формат. Если нужно присвоить ячейке текстовый формат, записывается так: Range("A1").NumberFormat = "@". Общий формат: Range("A1").NumberFormat = "General".
Offset Возвращает объект Range, смещенный относительно первоначального диапазона на указанное количество строк и столбцов. Подробнее…
Resize Изменяет размер первоначального диапазона до указанного количества строк и столбцов. Строки добавляются или удаляются снизу, столбцы – справа. Подробнее…
Row Возвращает номер строки ячейки (первой строки диапазона). Подробнее…
RowHeight Возвращает или задает высоту ячейки в пунктах (высоту всех строк в указанном диапазоне).
Text Возвращает форматированный текст, содержащийся в ячейке. Свойство Text диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковое содержимое и один формат. Предназначено только для чтения. Подробнее…
Value Возвращает или задает значение ячейки, в том числе с отображением значений в формате Currency и Date. Тип данных Variant. Value является свойством ячейки по умолчанию, поэтому в коде его можно не указывать.
Value2 Возвращает или задает значение ячейки. Тип данных Variant. Значения в формате Currency и Date будут отображены в виде чисел с типом данных Double.
VerticalAlignment Возвращает или задает значение вертикального выравнивания содержимого ячейки (диапазона). Подробнее…

В таблице представлены не все свойства объекта Range. С полным списком вы можете ознакомиться не сайте разработчика.

Простые примеры для начинающих

Вы можете скопировать примеры кода VBA Excel в стандартный модуль и запустить их на выполнение. Как создать стандартный модуль и запустить процедуру на выполнение, смотрите в статье VBA Excel. Начинаем программировать с нуля.

Учтите, что в одном программном модуле у всех процедур должны быть разные имена. Если вы уже копировали в модуль подпрограммы с именами Primer1, Primer2 и т.д., удалите их или создайте еще один стандартный модуль.

Форматирование ячеек

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

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

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

29

30

31

32

33

34

35

36

37

38

Sub Primer1()

MsgBox «Зальем ячейку A1 зеленым цветом и запишем в ячейку B1 текст: «Ячейка A1 зеленая!»»

Range(«A1»).Interior.Color = vbGreen

Range(«B1»).Value = «Ячейка A1 зеленая!»

MsgBox «Сделаем высоту строки, в которой находится ячейка A2, в 2 раза больше высоты ячейки A1, « _

& «а в ячейку B1 вставим текст: «Наша строка стала в 2 раза выше первой строки!»»

Range(«A2»).RowHeight = Range(«A1»).RowHeight * 2

Range(«B2»).Value = «Наша строка стала в 2 раза выше первой строки!»

MsgBox «Запишем в ячейку A3 высоту 2 строки, а в ячейку B3 вставим текст: «Такова высота второй строки!»»

Range(«A3»).Value = Range(«A2»).RowHeight

Range(«B3»).Value = «Такова высота второй строки!»

MsgBox «Применим к столбцу, в котором содержится ячейка B1, метод AutoFit для автоподбора ширины»

Range(«B1»).EntireColumn.AutoFit

MsgBox «Выделим текст в ячейке B2 красным цветом и выровним его по центру (по вертикали)»

Range(«B2»).Font.Color = vbRed

Range(«B2»).VerticalAlignment = xlCenter

MsgBox «Добавим к ячейкам диапазона A1:B3 границы»

Range(«A1:B3»).Borders.LineStyle = True

MsgBox «Сделаем границы ячеек в диапазоне A1:B3 двойными»

Range(«A1:B3»).Borders.LineStyle = xlDouble

MsgBox «Очистим ячейки диапазона A1:B3 от заливки, выравнивания, границ и содержимого»

Range(«A1:B3»).Clear

MsgBox «Присвоим высоте второй строки высоту первой, а ширине второго столбца — ширину первого»

Range(«A2»).RowHeight = Range(«A1»).RowHeight

Range(«B1»).ColumnWidth = Range(«A1»).ColumnWidth

MsgBox «Демонстрация форматирования ячеек закончена!»

End Sub

Вычисления в ячейках (свойство Value)

Запись двух чисел в ячейки, вычисление их произведения, вставка в ячейку формулы, очистка ячеек.

Обратите внимание, что разделителем дробной части у чисел в VBA Excel является точка, а не запятая.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

Sub Primer2()

MsgBox «Запишем в ячейку A1 число 25.3, а в ячейку B1 — число 34.42»

Range(«A1»).Value = 25.3

Range(«B1»).Value = 34.42

MsgBox «Запишем в ячейку C1 произведение чисел, содержащихся в ячейках A1 и B1»

Range(«C1»).Value = Range(«A1»).Value * Range(«B1»).Value

MsgBox «Запишем в ячейку D1 формулу, которая перемножает числа в ячейках A1 и B1»

Range(«D1»).Value = «=A1*B1»

MsgBox «Заменим содержимое ячеек A1 и B1 на числа 6.258 и 54.1, а также активируем ячейку D1»

Range(«A1»).Value = 6.258

Range(«B1»).Value = 54.1

Range(«D1»).Activate

MsgBox «Мы видим, что в ячейке D1 произведение изменилось, а в строке состояния отображается формула; « _

& «следующим шагом очищаем задействованные ячейки»

Range(«A1:D1»).Clear

MsgBox «Демонстрация вычислений в ячейках завершена!»

End Sub

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

Различие свойств Text, Value и Value2

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

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

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

Sub Primer3()

‘Присваиваем ячейкам всей таблицы общий формат на тот

‘случай, если формат отдельных ячеек ранее менялся

Range(«A1:E4»).NumberFormat = «General»

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

Range(«A1:E4»).Borders.LineStyle = True

‘Создаем строку заголовков

Range(«A1») = «Значение»

Range(«B1») = «Код формата» ‘формат соседней ячейки в столбце A

Range(«C1») = «Свойство Text»

Range(«D1») = «Свойство Value»

Range(«E1») = «Свойство Value2»

‘Назначаем строке заголовков жирный шрифт

Range(«A1:E1»).Font.Bold = True

‘Задаем форматы ячейкам A2, A3 и A4

‘Ячейка A2 — числовой формат с разделителем триад и двумя знаками после запятой

‘Ячейка A3 — формат даты «ДД.ММ.ГГГГ»

‘Ячейка A4 — текстовый формат

Range(«A2»).NumberFormat = «# ##0.00»

Range(«A3»).NumberFormat = «dd.mm.yyyy»

Range(«A4»).NumberFormat = «@»

‘Заполняем ячейки A2, A3 и A4 значениями

Range(«A2») = 2362.4568

Range(«A3») = CDate(«01.01.2021»)

‘Функция CDate преобразует текстовый аргумент в формат даты

Range(«A4») = «Озеро Байкал»

‘Заполняем ячейки B2, B3 и B4 кодами форматов соседних ячеек в столбце A

Range(«B2») = Range(«A2»).NumberFormat

Range(«B3») = Range(«A3»).NumberFormat

Range(«B4») = Range(«A4»).NumberFormat

‘Присваиваем ячейкам C2-C4 значения свойств Text ячеек A2-A4

Range(«C2») = Range(«A2»).Text

Range(«C3») = Range(«A3»).Text

Range(«C4») = Range(«A4»).Text

‘Присваиваем ячейкам D2-D4 значения свойств Value ячеек A2-A4

Range(«D2») = Range(«A2»).Value

Range(«D3») = Range(«A3»).Value

Range(«D4») = Range(«A4»).Value

‘Присваиваем ячейкам E2-E4 значения свойств Value2 ячеек A2-A4

Range(«E2») = Range(«A2»).Value2

Range(«E3») = Range(«A3»).Value2

Range(«E4») = Range(«A4»).Value2

‘Применяем к таблице автоподбор ширины столбцов

Range(«A1:E4»).EntireColumn.AutoFit

End Sub

Результат работы кода:

Сравнение свойств ячейки Text, Value и Value2

В таблице наглядно видна разница между свойствами Text, Value и Value2 при применении их к ячейкам с отформатированным числом и датой. Свойство Text еще отличается от Value и Value2 тем, что оно предназначено только для чтения.


Содержание

  1. Свойство Worksheet.Cells (Excel)
  2. Синтаксис
  3. Замечания
  4. Пример
  5. Поддержка и обратная связь
  6. VBA Code
  7. No Cell Object
  8. Contents of a Cell
  9. Text Property
  10. Range Object
  11. Cells Property
  12. Range Property
  13. Selection Property
  14. Relative References
  15. Total number of populated cells
  16. Window Object Only
  17. Counting
  18. Range of a Range
  19. Range.Address
  20. Range.AddressLocal
  21. XlCellType enumeration (Excel)
  22. Support and feedback
  23. Перечисление XlCellType (Excel)
  24. Поддержка и обратная связь
  25. Excel VBA Ranges and Cells
  26. Ranges and Cells in VBA
  27. Cell Address
  28. A1 Notation
  29. R1C1 Notation
  30. Range of Cells
  31. A1 Notation
  32. R1C1 Notation
  33. Writing to Cells
  34. Reading from Cells
  35. Non Contiguous Cells
  36. VBA Coding Made Easy
  37. Intersection of Cells
  38. Offset from a Cell or Range
  39. Offset Syntax
  40. Offset from a cell
  41. Offset from a Range
  42. Setting Reference to a Range
  43. Resize a Range
  44. Resize Syntax
  45. OFFSET vs Resize
  46. All Cells in Sheet
  47. UsedRange
  48. CurrentRegion
  49. Range Properties
  50. Last Cell in Sheet
  51. Last Used Row Number in a Column
  52. Last Used Column Number in a Row
  53. Cell Properties
  54. Common Properties
  55. Cell Font
  56. Copy and Paste
  57. Paste All
  58. Paste Special
  59. AutoFit Contents
  60. More Range Examples
  61. For Each
  62. Range Address
  63. Range to Array
  64. Array to Range
  65. Sum Range
  66. Count Range
  67. VBA Code Examples Add-in

Свойство Worksheet.Cells (Excel)

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

Синтаксис

выражение.Cells

Выражение Переменная, представляющая объект Worksheet .

Замечания

Так как элемент по умолчанию объекта Range направляет вызовы с параметрами в свойство Item, можно указать индекс строки и столбца сразу после ключевого слова Cells, вместо явного вызова свойства Item.

При использовании этого свойства без квалификатора объекта возвращается объект Range, который представляет все ячейки на активном листе.

Пример

В этом примере размер шрифта ячейки C5 на листе 1 активной книги устанавливается в 14 пунктов.

В этом примере формула очищается в ячейке 1 на листе 1 активной книги.

В этом примере шрифт и размер шрифта для каждой ячейки на листе Sheet1 устанавливается значение Arial из 8 точек.

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

В этом примере выполняется просмотр столбца C активного листа, и для каждой ячейки с комментарием текст примечания помещается в столбец D и удаляется комментарий из столбца C.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Code

No Cell Object

There is no Cell object nor is there a Cells collection.
Individual cells are treated as Range objects that refer to one cell.

Contents of a Cell

The easiest way to find what the contents of a cell are is to use the Visual Basic TypeName function

Text Property

You can assign a value to a cell using its Value property.
You can give a cell a number format by using its NumberFormat property.
The Text property of a cell returns the formatted appearance of the contents of a cell.

Range Object

The Range object can consist of individual cells or groups of cells.
Even an entire row or column is considered to be a range.
Although Excel can work with three dimensional formulas the Range object in VBA is limited to a range of cells on a single worksheet.
It is possible to edit a range either using a Range object directly (e.g. Range(«A1»).BackColor ) or by using the ActiveCell or Selection methods (e.g. ActiveCell.BackColor )

Cells Property

When the cells property is applied to a Range object the same object is returned.
It does have some uses though:

Range.Cells.Count — The total number of cells in the range.

Range.Cells( row, column ) — To refer to a specific cell within a range.

To loop through a range of cells

Cells automatically refer to the active worksheet.
If you want to access cells on another worksheet then the correct code is:

Range Property

When Range is not prefixed and used in a worksheet module, then it refers to that specific worksheet and not the active worksheet.

Selection Property

Selection will return a range of cells
Be aware that the Selection will not refer to a Range object if another type of object, such as a chart or shape is currently selected.
Using the Selection object performs an operation on the currently selected cells.
If a range of cells has not been selected prior to this command, then the active cell is used.

It is always worth checking what is currently selected before using the Selection property.

Relative References

It is important to remember that when a Cells property or a Range property is applied to a Range object, all the references are relative to the upper-left corner of that range.

ActiveCell returns a reference to the currently active cell
This will only ever return a single cell, even when a range of cells is selected.
The active cell will always be one of the corner cells of a range of cells. — will it what if you use the keyboard ??

Total number of populated cells

Window Object Only

This property applies only to a window object
This will enter the value 12 into the range that was selected before a non-range object was selected.

Window.RangeSelection property is read-only and returns a Range object that represents the selected cells on the worksheet in the active window.
If a graphic object is active or selected then this will returns the range of cells that was selected before the graphic object was selected.

Counting

Range of a Range

It is possible to treat a Range as if it was the top left cell in the worksheet.
This can be used to return a reference to the upper left cell of a Range object
The following line of code would select cell «C3».

Remember that cells are numbered starting from A1 and continuing right to the end of the row before moving to the start of the next row.

An alternative to this is to use the Offset which is more intuitive.

Range.Address

The Address method returns the address of a range in the form of a string.

Using the parameters allows you to control the transformation into a string (absolute vs relative).

RowAbsolute — True or False, default is True
ColumnAbsolute — True or False, default is True
ReferenceStyle — xlReferenceStyle.xlA1
External — True to return an external reference, default is false
RelativeTo — Range representing a relative to cell. Only relevant when ReferenceStyle = xlR1C1

Range.AddressLocal

This is similar to Address but it returns the address in the regional format of the language of the particular country.

Источник

XlCellType enumeration (Excel)

Specifies the type of cells.

Name Value Description
xlCellTypeAllFormatConditions -4172 Cells of any format.
xlCellTypeAllValidation -4174 Cells having validation criteria.
xlCellTypeBlanks 4 Empty cells.
xlCellTypeComments -4144 Cells containing notes.
xlCellTypeConstants 2 Cells containing constants.
xlCellTypeFormulas -4123 Cells containing formulas.
xlCellTypeLastCell 11 The last cell in the used range.
xlCellTypeSameFormatConditions -4173 Cells having the same format.
xlCellTypeSameValidation -4175 Cells having the same validation criteria.
xlCellTypeVisible 12 All visible cells.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Перечисление XlCellType (Excel)

Указывает тип ячеек.

Имя Значение Описание
xlCellTypeAllFormatConditions -4172 Ячейки любого формата.
xlCellTypeAllValidation -4174 Ячейки с критериями проверки.
xlCellTypeBlanks 4 Пустые ячейки.
xlCellTypeComments -4144 Ячейки, содержащие заметки.
xlCellTypeConstants 2 Ячейки, содержащие константы.
xlCellTypeFormulas -4123 Ячейки, содержащие формулы.
xlCellTypeLastCell 11 Последняя ячейка в используемом диапазоне.
xlCellTypeSameFormatConditions -4173 Ячейки с одинаковым форматом.
xlCellTypeSameValidation -4175 Ячейки с одинаковыми критериями проверки.
xlCellTypeVisible 12 Все видимые ячейки.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Excel VBA Ranges and Cells

In this Article

Ranges and Cells in VBA

Excel spreadsheets store data in Cells. Cells are arranged into Rows and Columns. Each cell can be identified by the intersection point of it’s row and column (Exs. B3 or R3C2).

An Excel Range refers to one or more cells (ex. A3:B4)

Cell Address

A1 Notation

In A1 notation, a cell is referred to by it’s column letter (from A to XFD) followed by it’s row number(from 1 to 1,048,576). This is called a cell address.

In VBA you can refer to any cell using the Range Object.

R1C1 Notation

In R1C1 Notation a cell is referred by R followed by Row Number then letter ‘C’ followed by the Column Number. eg B4 in R1C1 notation will be referred by R4C2. In VBA you use the Cells Object to use R1C1 notation:

Range of Cells

A1 Notation

To refer to a more than one cell use a “:” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:

R1C1 Notation

To refer to a more than one cell use a “,” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:

Writing to Cells

To write values to a cell or contiguous group of cells, simple refer to the range, put an = sign and then write the value to be stored:

Reading from Cells

To read values from cells, simple refer to the variable to store the values, put an = sign and then refer to the range to be read:

Note: To store values from a range of cells, you need to use an Array instead of a simple variable.

Non Contiguous Cells

To refer to non contiguous cells use a comma between the cell addresses:

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Intersection of Cells

To refer to non contiguous cells use a space between the cell addresses:

Offset from a Cell or Range

Using the Offset function, you can move the reference from a given Range (cell or group of cells) by the specified number_of_rows, and number_of_columns.

Offset Syntax

Offset from a cell

Offset from a Range

Setting Reference to a Range

To assign a range to a range variable: declare a variable of type Range then use the Set command to set it to a range. Please note that you must use the SET command as RANGE is an object:

Resize a Range

Resize method of Range object changes the dimension of the reference range:

Top-left cell of the Resized range is same as the top-left cell of the original range

Resize Syntax

OFFSET vs Resize

Offset does not change the dimensions of the range but moves it by the specified number of rows and columns. Resize does not change the position of the original range but changes the dimensions to the specified number of rows and columns.

All Cells in Sheet

The Cells object refers to all the cells in the sheet (1048576 rows and 16384 columns).

UsedRange

UsedRange property gives you the rectangular range from the top-left cell used cell to the right-bottom used cell of the active sheet.

CurrentRegion

CurrentRegion property gives you the contiguous rectangular range from the top-left cell to the right-bottom used cell containing the referenced cell/range.

Range Properties

You can get Address, row/column number of a cell, and number of rows/columns in a range as given below:

Last Cell in Sheet

You can use Rows.Count and Columns.Count properties with Cells object to get the last cell on the sheet:

Last Used Row Number in a Column

END property takes you the last cell in the range, and End(xlUp) takes you up to the first used cell from that cell.

Last Used Column Number in a Row

END property takes you the last cell in the range, and End(xlToLeft) takes you left to the first used cell from that cell.

You can also use xlDown and xlToRight properties to navigate to the first bottom or right used cells of the current cell.

Cell Properties

Common Properties

Here is code to display commonly used Cell Properties

Cell Font

Cell.Font object contains properties of the Cell Font:

Copy and Paste

Paste All

Ranges/Cells can be copied and pasted from one location to another. The following code copies all the properties of source range to destination range (equivalent to CTRL-C and CTRL-V)

Paste Special

Selected properties of the source range can be copied to the destination by using PASTESPECIAL option:

Here are the possible options for the Paste option:

AutoFit Contents

Size of rows and columns can be changed to fit the contents using AutoFit:

More Range Examples

It is recommended that you use Macro Recorder while performing the required action through the GUI. It will help you understand the various options available and how to use them.

For Each

It is easy to loop through a range using For Each construct as show below:

At each iteration of the loop one cell in the range is assigned to the variable cell and statements in the For loop are executed for that cell. Loop exits when all the cells are processed.

Sort is a method of Range object. You can sort a range by specifying options for sorting to Range.Sort. The code below will sort the columns A:C based on key in cell C2. Sort Order can be xlAscending or xlDescending. Header:= xlYes should be used if first row is the header row.

Find is also a method of Range Object. It find the first cell having content matching the search criteria and returns the cell as a Range object. It return Nothing if there is no match.

Use FindNext method (or FindPrevious) to find next(previous) occurrence.

Following code will change the font to “Arial Black” for all cells in the range which start with “John”:

Following code will replace all occurrences of “To Test” to “Passed” in the range specified:

It is important to note that you must specify a range to use FindNext. Also you must provide a stopping condition otherwise the loop will execute forever. Normally address of the first cell which is found is stored in a variable and loop is stopped when you reach that cell again. You must also check for the case when nothing is found to stop the loop.

Range Address

Use Range.Address to get the address in A1 Style

Use xlReferenceStyle (default is xlA1) to get addres in R1C1 style

This is useful when you deal with ranges stored in variables and want to process for certain addresses only.

Range to Array

It is faster and easier to transfer a range to an array and then process the values. You should declare the array as Variant to avoid calculating the size required to populate the range in the array. Array’s dimensions are set to match number of values in the range.

Array to Range

After processing you can write the Array back to a Range. To write the Array in the example above to a Range you must specify a Range whose size matches the number of elements in the Array.

Use the code below to write the Array to the range D1:D5:

Please note that you must Transpose the Array if you write it to a row.

Sum Range

You can use many functions available in Excel in your VBA code by specifying Application.WorkSheetFunction. before the Function Name as in the example above.

Count Range

Written by: Vinamra Chandra

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Понравилась статья? Поделить с друзьями:
  • Vba excel trim что это
  • Vba excel xml createelement
  • Vba excel variant массив
  • Vba excel trim описание
  • Vba excel xlup что такое