Set string vba excel

In this Article

  • Set Cell Value
    • Range.Value & Cells.Value
    • Set Multiple Cells’ Values at Once
    • Set Cell Value – Text
    • Set Cell Value – Variable
  • Get Cell Value
    • Get ActiveCell Value
    • Assign Cell Value to Variable
  • Other Cell Value Examples
    • Copy Cell Value
    • Compare Cell Values

This tutorial will teach you how to interact with Cell Values using VBA.

Set Cell Value

To set a Cell Value, use the Value property of the Range or Cells object.

Range.Value & Cells.Value

There are two ways to reference cell(s) in VBA:

  • Range Object – Range(“A2”).Value
  • Cells Object – Cells(2,1).Value

The Range object allows you to reference a cell using the standard “A1” notation.

This will set the range A2’s value = 1:

Range("A2").Value = 1

The Cells object allows you to reference a cell by it’s row number and column number.

This will set range A2’s value = 1:

Cells(2,1).Value = 1

Notice that you enter the row number first:

Cells(Row_num, Col_num)

Set Multiple Cells’ Values at Once

Instead of referencing a single cell, you can reference a range of cells and change all of the cell values at once:

Range("A2:A5").Value = 1

Set Cell Value – Text

In the above examples, we set the cell value equal to a number (1).  Instead, you can set the cell value equal to a string of text.  In VBA, all text must be surrounded by quotations:

Range("A2").Value = "Text"

If you don’t surround the text with quotations, VBA will think you referencing a variable…

Set Cell Value – Variable

You can also set a cell value equal to a variable

Dim strText as String
strText = "String of Text"

Range("A2").Value = strText

Get Cell Value

You can get cell values using the same Value property that we used above.

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!

automacro

Learn More

Get ActiveCell Value

To get the ActiveCell value and display it in a message box:

MsgBox ActiveCell.Value

Assign Cell Value to Variable

To get a cell value and assign it to a variable:

Dim var as Variant

var = Range("A1").Value

Here we used a variable of type Variant. Variant variables can accept any type of values.  Instead, you could use a String variable type:

Dim var as String

var = Range("A1").Value

A String variable type will accept numerical values, but it will store the numbers as text.

If you know your cell value will be numerical, you could use a Double variable type (Double variables can store decimal values):

Dim var as Double

var = Range("A1").Value

However, if you attempt to store a cell value containing text in a double variable, you will receive an type mismatch error:

get cell value assign variable

Other Cell Value Examples

VBA Programming | Code Generator does work for you!

Copy Cell Value

It’s easy to set a cell value equal to another cell value (or “Copy” a cell value):

Range("A1").Value = Range("B1").Value

You can even do this with ranges of cells (the ranges must be the same size):

Range("A1:A5").Value = Range("B1:B5").Value

Compare Cell Values

You can compare cell values using the standard comparison operators.

Test if cell values are equal:

MsgBox Range("A1").Value = Range("B1").Value

Will return TRUE if cell values are equal. Otherwise FALSE.

You can also create an If Statement to compare cell values:

If Range("A1").Value > Range("B1").Value Then

  Range("C1").Value = "Greater Than"

Elseif Range("A1").Value = Range("B1").Value Then

  Range("C1").Value = "Equal"

Else

  Range("C1").Value = "Less Than"

End If

You can compare text in the same way (Remember that VBA is Case Sensitive)

Хитрости »

1 Май 2011              225471 просмотров


Что такое переменная и как правильно её объявить?

Переменная — это некий контейнер, в котором VBA хранит данные. Если подробнее, то это как коробочка, в которую Вы можете положить что-то на хранение, а затем по мере необходимости достать. Только в данном случае в переменной мы храним число, строку или иные данные, которые затем можем извлекать из неё и использовать в коде по мере необходимости.

Для чего нужна переменная? Чтобы хранить значение и применить его позже в любой момент. Например, в ячейке А1 записана сумма, а нажатием на кнопку запускается обновление отчета. После обновления отчета сумма в А1 изменится. Необходимо сверить сумму до обновления с суммой после и в зависимости от этого сделать какое-либо действие. Переменная как раз позволит запомнить значение ячейки до того, как она обновится и использовать именно это значение после обновления.


  • Требования к переменным
  • Типы данных, хранимых в переменных
  • Как объявлять переменные
  • Как правильно назвать переменную
  • Пример использования переменных
  • Константы

В качестве имен переменных можно использовать символы букв и числа, но первой в имени переменной всегда должна быть буква. Не допускается использование точки, запятой, пробела и иных знаков препинания, кроме нижнего подчеркивания. Длина имени не должна превышать 254 символов. Так же нельзя использовать в качестве имен для переменных зарезервированные константы редактора VBA(например Sub, Msgbox, ubound, Date и т.п.). Так же для переменных неважен регистр букв.

 
Теперь рассмотрим основные декларированные в VBA

типы данных, которые можно хранить в переменных:

Тип данных Занимает байт в памяти Пределы значений
Byte 1 Целые числа от 0 до 255
Boolean 2 True или False
Integer 2 Целые числа от (-32768) до 32767
Long 4 Целые числа от (-2147483648) до 2147483647
Single 4 От (–3.402823Е+38) до (–1.401298Е-45) и от 1.401298Е-45 до 3.402823Е+38
Double 8 От ±1.79769313486232Е+308 до ±4.94065645841247Е-324
Decimal 12 От ±79228162514264337593543950335 без десятичных знаков до ±7,9228162514264337593543950335 с 28-ю знаками после запятой
Currency 8 От (–922337203685477.5808) до 922337203685477.5807
Date 8 От 01.01.100 до 31.12.9999(не надо путать с датами в Excel — 01.01.1900 до 31.12.9999)
String 10(+длина строки) От 0 до 65400 символов для фиксированных строк и чуть более 2 млрд. для строк переменной длины
Object 4 Любой объект
Array Определяется кол-вом и размером элементов
Variant от 16-ти Любой из встроенных типов данных

Как видно из таблицы больше всего памяти занимает Variant. Притом это если он хранит числовые данные. Если же такая переменная будет хранить данные строкового типа(текст), то размер занимаемой памяти будет измеряться уже начиная с 22 байт + длина строки, хранящейся в переменной. Чем больше памяти занимает переменная, тем дольше она инициализируется в памяти и тем медленнее код будет выполняться. Вот поэтому и важно явно задавать тип данных, хранимых в переменной — это называется объявить переменную.

Тип данных Decimal больше не используется, поэтому объявить переменную данного типа в VBA не получится — подобная попытка приведет к синтаксической ошибке. Для работы с данными типа Decimal переменную необходимо изначально объявить как Variant или вообще без типа (например Dim a), т.к. тип данных Variant используется в VBA по умолчанию и принимает любой тип данных.

Так же переменным можно назначать и другие типы данных, которых нет в таблице выше — это типы, которые поддерживаются объектной моделью приложений, к которым «подключен» VBA. Например, если зайти в VBA из Excel, то библиотека типов объектной модели Excel подключена по умолчанию и для переменных становится доступно множество типов этой объектной модели. Многие из них знакомы всем: Workbook, Worksheet, Range, Cells, Chart и т.д. Т.е. это книги, листы, ячейки, диаграммы. Типов много, почти на каждый объект и коллекцию. Рассматривать здесь все бессмысленно. Могу лишь привести пару строк кода:

Dim rRange as Range 'назначили переменной тип ячейка/диапазон
Set rRange = Range("A1") 'присвоили ссылку на ячейку A1 текущего листа

Про объявление переменных подробно написано чуть ниже.
А более подробно про обращение к диапазонам из VBA можно почитать в этой статье: Как обратиться к диапазону из VBA

как объявлять переменные

На самом деле все очень просто. Это делается при помощи операторов области действия: Dim, Public,Static и оператора присвоения типа As. Самый распространенный оператор — Dim. Его и возьмем в качестве примера. Синтаксис объявления:

[оператор области действия] Имя_переменной As [тип данных]

Очень частая ошибка при объявлении переменных, совершаемая начинающими изучать VBA:

Dim MyVar1, MyVar2, MyVar3 As Integer

Вроде бы исходя из логики всем переменным присвоен тип данных Integer. Но это ошибочное суждение. Тип Integer присвоен только последней переменной, к которой он «привязан» оператором AsMyVar3. Все остальные переменные имеют тип данных Variant. Т.е. если Вы не задаете каждой переменной свой тип хранимых данных явно(т.е. не указываете для неё тип данных через As), то VBA сам присваивает для такой переменной тип данных Variant, т.к. он может хранить любой тип данных. А вот так выглядит правильное присвоение типа данных:

Dim MyVar1 As Integer, MyVar2 As Integer, MyVar3 As Integer

Это и есть объявление переменных. Т.е. сначала идет оператор области действия (Dim, Public,Static), сразу за ним имя переменной, затем оператор As и тип.
Но это не все. Некоторые типы переменным можно присваивать еще короче — даже без оператора As:

Dim MyVar1%, MyVar2%, MyVar3%

Всего шесть типов, которые можно объявить подобным методом:
! — Single
# — Double
$ — String
% — Integer
& — Long
@ — Currency
На что стоит обратить внимание, при объявлении переменных подобным образом: между именем переменной и знаком типа не должно быть пробелов.
Я лично в большинстве статей предпочитаю использовать первый метод, т.е. полное указание типа. Это читабельнее и понятнее. В каких-то проектах могу использовать краткое указание, в общих(разработка в команде) — полное. В своих кодах Вы вправе использовать удобный Вам метод — ошибки не будет.

Теперь разберемся с операторами области действия(Dim, Public и Static):

  • Dim — данный оператор используется для объявления переменной, значение которой будет храниться только в той процедуре, внутри которой данная переменная объявлена. Во время запуска процедуры такая переменная инициализируется в памяти и использовать её значение можно внутри только этой процедуры, а по завершению процедуры переменная выгружается из памяти(обнуляется) и данные по ней теряются. Переменную, объявленную подобным образом еще называют локальной переменной. Однако с помощью данного оператора можно объявить переменную, которая будет доступна в любой процедуре модуля. Необходимо объявить переменную вне процедуры — в области объявлений(читать как первой строкой в модуле, после строк объявлений типа — Option Explicit). Тогда значение переменной будет доступно в любой процедуре лишь того модуля, в котором данная переменная была объявлена. Такие переменные называются переменными уровня модуля. Также для использования переменных во всех процедурах и функциях одного конкретного модуля можно использовать оператор Private. Но он в данном случае ничем не отличается от Dim, а пишется длиннее :) Плюс, Private нельзя использовать внутри процедуры или функции(только в области объявлений), что еще больше сужает её применимость. По сути чаще этот оператор применяется к функциям и процедурам(об этом см.ниже)
  • Static — данный оператор используется для объявления переменной, значение которой предполагается использовать внутри конкретной процедуры, но не теряя значения данной переменной по завершении процедуры. Переменные данного типа обычно используют в качестве накопительных счетчиков. Такая переменная инициализируется в памяти при первом запуске процедуры, в которой она объявлена. По завершении процедуры данные по переменной не выгружаются из памяти, но однако они не доступны в других процедурах. Как только Вы запустите процедуру с этой переменной еще раз — данные по такой переменной будут доступны в том виде, в котором были до завершения процедуры. Выгружается из памяти такая переменная только после закрытия проекта(книги с кодом).
  • Public — данный оператор используется для объявления переменной, значение которой будет доступно в любой процедуре проекта(в обычных модулях, модулях класса, модулях форм, модулях листов и книг). Переменная, объявленная подобным образом, должна быть объявлена вне процедуры — в области объявлений. Такая переменная загружается в память во время загрузки проекта(при открытии книги) и хранит значение до выгрузки проекта(закрытия книги). Использовать её можно в любом модуле и любой процедуре проекта. Важно: объявлять подобным образом переменную необходимо строго в стандартном модуле. Такие переменные называются переменными уровня проекта. В простонародье такие переменные еще называют глобальными(возможно из-за того, что раньше подобные переменные объявлялись при помощи оператора Global, который в настоящее время устарел и не используется).
    Для большего понимания того, где и как объявлять переменные уровня проекта два небольших примера.
    Неправильное объявление

    Option Explicit
     
    Sub main()
    Public MyVariable As String
    MyVariable = "Глобальная переменная"
    'показываем текущее значение переменной
    MsgBox MyVariable
    'пробуем изменить значение переменной
    Call sub_main
    'показываем измененное значение переменной
    MsgBox MyVariable
    End Sub
    'доп.процедура изменения значения переменной
    Sub ChangeMyVariable()
    MyVariable = "Изменили её значение"
    End Sub

    переменные не будут видны во всех модулях всех процедур и функций проекта, потому что:
    1. Оператор Public недопустим внутри процедуры(между Sub и End Sub), поэтому VBA при попытке выполнения такой процедуры обязательно выдаст ошибку — Invalid Attribut in Sub or Function.
    2. Даже если Public заменить на Dim — это уже будет переменная уровня процедуры и для других процедур будет недоступна.
    3. Т.к. объявление неверное — вторая процедура(ChangeMyVariable) ничего не знает о переменной MyVariable и естественно, не сможет изменить именно её.
    Правильное объявление

    'выше глобальных переменных и констант могут быть только декларации:
    Option Explicit     'принудительное объявление переменных
    Option Base 1       'нижняя граница объявляемых массивов начинается с 1
    Option Compare Text 'сравнение текста без учета регистра
    'глобальная переменная - первой строкой, выше всех процедур
    Public MyVariable As String
    'далее процедуры и функции
    Sub main()
        MyVariable = "Глобальная переменная"
        'показываем текущее значение переменной
        MsgBox MyVariable, vbInformation, "www.excel-vba.ru"
        'пробуем изменить значение переменной
        Call ChangeMyVariable
        'показываем измененное значение переменной
        MsgBox MyVariable, vbInformation, "www.excel-vba.ru"
    End Sub
    'доп.процедура изменения значения переменной
    Sub ChangeMyVariable()
        MyVariable = "Изменили её значение"
    End Sub

    Если при этом вместо Public записать Dim, то эта переменная будет доступна из всех функций и процедур того модуля, в котором записана, но недоступна для функций и процедур других модулей.
    Переменные уровня проекта невозможно объявить внутри модулей классов(ClassModule, ЭтаКнига(ThisWorkbook), модулей листов, модулей форм(UserForm) — подробнее про типы модулей: Что такое модуль? Какие бывают модули?)

  • Операторы области действия так же могут применяться и к процедурам. Для процедур доступен еще один оператор области действия — Private. Объявленная подобным образом процедура доступна только из того модуля, в котором записана и такая процедура не видна в диалоговом окне вызова макросов(Alt+F8)
  • 'процедура записана в Module1
    'эта процедура будет доступна для вызова исключительно из процедур в этом же модуле
    'но не будет доступна при вызове из других модулей
    Private Sub PrivateMain()
        MsgBox "Процедура может быть вызвана только из модуля, в котором записана", vbInformation, "www.excel-vba.ru"
    End Sub
    'другая процедура, записанная в этом же модуле
    Sub CallPrivate()
        Call PrivateMain
    End Sub
    'эта процедура записана в другом модуле - Module2
    'при попытке вызова этой процедурой получим ошибку
    ' Sub or Function not defined
    ' потому что процедура PrivateMain объявлена только для Module1
    Sub CallPrivate_FromModule1()
        Call PrivateMain
    End Sub

    При этом, если из Excel нажать сочетание клавиш Alt+F8, то в окне будут доступны только CallPrivate_FromModule1 и CallPrivate. Процедура PrivateMain будет недоступна.

Как правильно назвать переменную:

«Что самое сложное в работе программиста? — выдумывать имена переменным.» :-)А ведь придумать имя переменной тоже не так-то просто. Можно, конечно, давать им имена типа: a, d, f, x, y и т.д.(я сам иногда так делаю, но либо в простых кодах, либо для специального запутывания кода). Но стоит задуматься: а как Вы с ними будете управляться в большом коде? Код строк на 10 еще потерпит такие имена, а вот более крупные проекты — не советовал бы я в них оперировать такими переменными. Вы сами запутаетесь какая переменная как объявлена и какой тип данных может хранить и что за значение ей присвоено. Поэтому лучше всего давать переменным осмысленные имена и следовать соглашению об именовании переменных. Что за соглашение? Все очень просто: перед основным названием переменной ставится префикс, указывающий на тип данных, который мы предполагаем хранить в данной переменной. Про имеющиеся типы данных я уже рассказал выше. А ниже приведена примерная таблица соответствий префиксов типам данных:

Префикс Тип хранимых данных
b Boolean
bt Byte
i Integer
l Long
s Single
d Double
c Currency
dt Date
str String
obj Object
v Variant

Лично я немного для себя её переделал, т.к. некоторые обозначения мне кажутся скудными. Например Double я обозначаю как dbl, а Single как sgl. Это мне кажется более наглядным.

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

DefBool B
Sub test()
    Dim bCheck
End Sub

Автоматически переменной bCheck будет присвоен тип Boolean, т.к. она начинается с буквы b — регистр здесь не имеет значения(впрочем как в VBA в целом). Оператор Def задается в области объявления. Можно задать не одну букву, а целый диапазон букв:

DefBool B-C
Sub test()
    Dim bCheck, cCheck
End Sub

Но я считаю, что одной буквы для одного типа вполне достаточно. Можно задать сразу несколько операторов Def.

DefBool B
DefStr S
Sub test()
    Dim bCheck, sCheck
End Sub

Ниже приведен полный перечень операторов типов и данные, которые задает каждый из них:
DefBool — Задает тип Boolean
DefByte — Задает тип Byte
DefCur — Задает тип Currency
DefDate — Задает тип Date
DefDbl — Задает тип Double
DefInt — Задает тип Integer
DefLng — Задает тип Long
DefObj — Задает тип Object
DefSng — Задает тип Single
DefStr — Задает тип String
DefVar — Задает тип Variant
По умолчанию в VBA применена инструкция DefVar для всех букв(иначе говоря для всех переменных, которым не назначен тип данных явно через оператор As).

Ну и немаловажный момент это непосредственно осмысленное имя переменной. Имя переменной должно примерно отражать то, что в ней будет храниться. Например, Вы создаете отчет и Вам надо объявить две переменные: одна имя листа, другая имя книги. Можно было сделать так: str1, str2. Коротко, здорово. Но если подумать — и как можно понять, какая из этих переменных что хранит? Никак. Надо просматривать код и вспоминать, какой переменной какое значение было присвоено. Не совсем удобно, правда? А если бы Вы задали имена так: strBookName, strSheetName, то вроде как более понятно, что мы в них будем хранить. Это удобно не только вам самим при работе с кодом, но и другим людям, которые, возможно в будущем будут пользоваться Вашим кодом. Им будет удобнее читать код, если он будет оформлен грамотно, а переменные названы осмысленно. И не стоит экономить на длине имени — имя должно быть понятным. Без фанатизма, конечно :-). Хоть VBA и позволяет нам создавать переменные длиной до 254 символов, но читать такую переменную так же неудобно, как и с одним символом. Но здесь уже все зависит от Ваших предпочтений и фантазии.
Небольшое дополнение: лучше привыкать давать названия переменным на латинице(т.е. английский алфавит), т.к. для VBA английский язык «родной» и лучше использовать его.

Небольшой пример использования переменных в кодах:
Sub main()
'объявляем переменные с назначением конкретных типов
'As String - текст
'As Long   - целое число
Dim sAddress As String, sNewAddress As String, sShName As String
Dim lRow As Long
Dim rRange as Range 'назначили переменной тип ячейка/диапазон
 
'присвоили переменной rRange ссылку на текущую выделенную ячейку
Set rRange = Selection
'меняем выделение - выделяем ячейку D9
Range("D9").Select
'назначаем переменной адрес выделенных ячеек
sAddress = Selection.Address
'назначаем переменной lRow значение первой строки выделенной области
lRow = Selection.Row
'показываем сообщение
MsgBox "Адрес выделенной области: " & sAddress, vbInformation, "www.excel-vba.ru"
MsgBox "Номер первой строки: " & lRow, vbInformation, "www.excel-vba.ru"
'назначаем другой переменной значение адреса ячейки A1
sNewAddress = "A1"
'выделяем ячейку, заданную переменной sNewAddres
Range(sNewAddress).Select
MsgBox "Адрес выделенной области: " & sNewAddress, vbInformation, "www.excel-vba.ru"
'выделяем изначально выделенную ячейку, используя переменную rRange
rRange.Select
MsgBox "Адрес выделенной области: " & rRange.Address, vbInformation, "www.excel-vba.ru"
'задаем значение переменной
sShName = "excel-vba"
'переименовываем активный лист на имя, заданное переменной
ActiveSheet.Name = sShName
End Sub

Просмотреть пошагово выполнение данного кода поможет статья: Отлов ошибок и отладка кода VBA
Важно! Назначение значений переменным задается при помощи знака равно(=). Однако, есть небольшой нюанс: для переменных типа Object(а так же других объектных типов(Workbook, Worksheet, Range, Cells, Chart и т.п.)) присвоение идет при помощи ключевого оператора Set:

'присвоили переменной rRange ссылку на текущую выделенную ячейку
Set rRange = Selection

это так же называется присвоением ссылки на объект. Почему именно ссылки? Все просто: при помещении в переменную непосредственно ячейки или диапазона(Set var = Range(«A1») или Set rRange = Selection) нет никакого запоминания самой ячейки. В переменную помещается лишь ссылка на эту ячейку(можете считать, что это как ссылка в формулах) со всеми вытекающими: такое назначение не запоминает свойства ячейки до или после — в переменной хранится ссылка на конкретную ячейку и доступ есть исключительно к свойствам ячейки на текущий момент. Чтобы запомнить для этой ячейки значение, цвет или даже адрес (а так же и другие свойства) до её изменения и применить запомненное даже после изменения/перемещения самой ячейки — необходимо запоминать в переменные именно свойства ячейки:

Sub main()
    Dim val, l_InteriorColor As Long, l_FontColor As Long
    Dim rRange As Range 'назначили переменной тип ячейка/диапазон
 
    'присвоили переменной rRange ссылку на активную ячейку
    Set rRange = ActiveCell
    'запоминаем свойства ячейки
    val = rRange.Value                      'значение
    l_InteriorColor = rRange.Interior.Color 'цвет заливки
    l_FontColor = rRange.Font.Color         'цвет шрифта
    'копируем другую ячейку и вставляем на место активной
    ActiveSheet.Range("D1").Copy rRange
 
    'проверяем, что rRange теперь имеет совершенно другие свойста - как у D1
    MsgBox "Значение rRange: " & rRange.Value & vbNewLine & _
           "Цвет заливки rRange: " & rRange.Interior.Color & vbNewLine & _
           "Цвет шрифта rRange: " & rRange.Font.Color & vbNewLine, vbInformation, "www.excel-vba.ru"
 
    'назначаем свойства из сохраненных в переменных
    rRange.Value = val                      'значение
    rRange.Interior.Color = l_InteriorColor 'цвет заливки
    rRange.Font.Color = l_FontColor         'цвет шрифта
 
    'проверяем, что rRange возвращены параметры до копирования
    MsgBox "Значение rRange: " & rRange.Value & vbNewLine & _
           "Цвет заливки rRange: " & rRange.Interior.Color & vbNewLine & _
           "Цвет шрифта rRange: " & rRange.Font.Color & vbNewLine, vbInformation, "www.excel-vba.ru"
End Sub

Это так же распространяется на все другие объекты. Т.е. те переменные, значения которым назначаются через оператор Set.
Для других же типов Set не нужен и в переменную значение заносится без этих нюансов.


Константы

Так же есть и иной вид «переменных» — константы. Это такая же переменная, только(как следует из её названия) — она не может быть изменена во время выполнения кода, т.к. является величиной постоянной и значение её назначается только один раз — перед выполнением кода.

Const sMyConst As String = "Имя моей программы"

Константам могут быть назначены данные тех же типов, что и для переменных, за исключением типа Object, т.к. Object это всегда ссылка на объект, который как правило обладает «динамическими»(т.е. обновляющимися) свойствами. А изменение для констант недопустимо.
Для дополнительной области видимости/жизни констант используется только Public. Если область видимости не указана, то константа будет доступна только из того модуля, в котором объявлена. Здесь обращаю внимание на то, что Dim уже не используется, т.к. Dim это идентификатор только для переменных. Пару важных отличий объявления констант от объявления переменных:

  • при объявлении константы необходимо обязательно указывать явно, что это константа ключевым словом Const
  • сразу в момент объявления необходимо назначить константе значение: = «Имя моей программы»

Во всем остальном объявление и применение констант идентично объявлению переменных. Коротко приведу пару примеров.
Если константа объявлена внутри процедуры:

Sub TestConst()
    Const sMyConst As String = "Имя моей программы"
    MsgBox sMyConst 'показываем сообщение с именем программы
End Sub

то она не может быть использована в другой процедуре:

Sub TestConst()
    Const sMyConst As String = "Имя моей программы"
    MsgBox sMyConst 'показываем сообщение с именем программы
End Sub
Sub TestConst2()
    MsgBox sMyConst 'вызовет ошибку Variable not defined
End Sub

Чтобы использовать одну константу во всех процедурах модуля(того, в котором она объявлена), необходимо объявить её в области объявлений:

Const sMyConst As String = "Имя моей программы"
Sub TestConst()
    MsgBox sMyConst 'показываем сообщение с именем программы
End Sub
Sub TestConst2()
    MsgBox sMyConst 'уже не вызовет ошибку Variable not defined
End Sub

Чтобы использовать одну константу во всех процедурах проекта(книги), необходимо объявить её как Public:

Public Const sMyConst As String = "Имя моей программы"
Sub TestConst()
    MsgBox sMyConst 'показываем сообщение с именем программы
End Sub
Sub TestConst2()
    MsgBox sMyConst 'не вызовет ошибку Variable not defined, даже если процедура в другом модуле
End Sub

Подробнее можно прочитать выше — как я уже писал для констант применяются те же правила, что и для переменных.

Также см.:
Variable not defined или что такое Option Explicit и зачем оно нужно?
Что такое модуль? Какие бывают модули?
Что такое макрос и где его искать?
Отлов ошибок и отладка кода VBA


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

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


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



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

I am trying to write a value to the «A1» cell, but am getting the following error:

Application-defined or object-defined error ‘1004’

I have tried many solutions on the net, but none are working. I am using excel 2007 and the file extensiton is .xlsm.

My code is as follows:

Sub varchanger()
On Error GoTo Whoa
Dim TxtRng  As Range

Worksheets("Game").Activate
ActiveSheet.Unprotect

Set TxtRng = ActiveWorkbook.Sheets("Game").Cells(1, 1)
TxtRng.Value = "SubTotal"

'Worksheets("Game").Range("A1") = "Asdf"

LetsContinue:
    Exit Sub
Whoa:
    MsgBox Err.number
    Resume LetsContinue
End Sub

Edit: After I get error if I click the caution icon and then select show calculation steps its working properly

asked Jul 19, 2012 at 19:57

knightrider's user avatar

knightriderknightrider

2,0531 gold badge16 silver badges29 bronze badges

12

I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you’re setting the TxtRng object, but not when you unprotect the sheet.

Try this:

Sub varchanger()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim TxtRng  As Range

    Set wb = ActiveWorkbook
    Set ws = wb.Sheets("Sheet1")
    'or ws.Unprotect Password:="yourpass"
    ws.Unprotect

    Set TxtRng = ws.Range("A1")
    TxtRng.Value = "SubTotal"
    'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
    ' or ws.Protect Password:="yourpass"
    ws.Protect

End Sub

If I run the sub with ws.Unprotect commented out, I get a run-time error 1004. (Assuming I’ve protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.

NOTES:

  1. I’m re-setting sheet protection after writing to the range. I’m assuming you want to do this if you had the sheet protected in the first place. If you are re-setting protection later after further processing, you’ll need to remove that line.
  2. I removed the error handler. The Excel error message gives you a lot more detail than Err.number. You can put it back in once you get your code working and display whatever you want. Obviously you can use Err.Description as well.
  3. The Cells(1, 1) notation can cause a huge amount of grief. Be careful using it. Range("A1") is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.

shareef's user avatar

shareef

9,06213 gold badges58 silver badges89 bronze badges

answered Jul 20, 2012 at 12:08

Jon Crowell's user avatar

Jon CrowellJon Crowell

21.5k14 gold badges88 silver badges110 bronze badges

2

I’ve had a few cranberry-vodkas tonight so I might be missing something…Is setting the range necessary? Why not use:

Activeworkbook.Sheets("Game").Range("A1").value = "Subtotal"

Does this fail as well?

Looks like you tried something similar:

'Worksheets("Game").Range("A1") = "Asdf"

However, Worksheets is a collection, so you can’t reference «Game». I think you need to use the Sheets object instead.

answered Jul 21, 2012 at 1:48

UberNubIsTrue's user avatar

0

replace
Range(«A1») = «Asdf»
with
Range(«A1»).value = «Asdf»

answered Apr 16, 2015 at 20:01

T. I. Troll's user avatar

try this instead

Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")

ADDITION

Maybe the file is corrupt — this has happened to me several times before and the only solution is to copy everything out into a new file.

Please can you try the following:

  • Save a new xlsm file and call it «MyFullyQualified.xlsm»
  • Add a sheet with no protection and call it «mySheet»
  • Add a module to the workbook and add the following procedure

Does this run?

 Sub varchanger()

 With Excel.Application
    .ScreenUpdating = True
    .Calculation = Excel.xlCalculationAutomatic
    .EnableEvents = True
 End With

 On Error GoTo Whoa:

    Dim myBook As Excel.Workbook
    Dim mySheet As Excel.Worksheet
    Dim Rng  As Excel.Range

    Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
    Set mySheet = myBook.Worksheets("mySheet")
    Set Rng = mySheet.Range("A1")

    'ActiveSheet.Unprotect


    Rng.Value = "SubTotal"

    Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"

LetsContinue:
        Exit Sub
Whoa:
        MsgBox Err.Number
        GoTo LetsContinue

End Sub

answered Jul 19, 2012 at 20:18

whytheq's user avatar

whytheqwhytheq

34k64 gold badges170 silver badges265 bronze badges

3

Key Notes

  • The value property can be used in both ways (you can read and write a value from a cell).
  • You can refer to a cell using Cells and Range Object to set a cell value (to Get and Change also).

To set a cell value, you need to use the “Value” property, and then you need to define the value that you want to set. Here I have used some examples to help you understand this.

1. Enter a Value in a Cell

Let’s say you need to enter the value “Done” in cell A1. In that case, the code would be something like the below:

Range("A1").Value = "Done"

As you can see, I have first defined the cell address where I want to add the value, and then the value property. In the end, I have assigned the value “Done” using an equal “=” sign enclosed in double quotation marks.

You can also use the “Cells” property, just like the following code.

Cells(1, 1).Value = "Done"

The above code also refers to cell A1.

Apart from this, there is one more way that you can use and that’s by not using the value property directly assigning the value to the cell.

Cells(1, 1) = "Done"

But this is recommended to use the value property to enter a value in a cell.

Now let’s say you want to enter a number in a cell. In that case, you don’t need to use double quotation marks. You can write the code like the following.

Range("A1") = 99

You can also DATE and NOW (VBA Functions) to enter a date or a timestamp in a cell using a VBA code.

Range("A1").Value = Date
Range("A2").Value = Now

And if you want to enter a value in the active cell then the code you need would be like:

ActiveCell.Value = Date

2. Using an Input Box

If you want a user to specify a value to enter in a cell you can use an input box. Let’s say you want to enter the value in cell A1, the code would be like this:

Range("A1").Value = _
InputBox(Prompt:="Type the value you want enter in A1.")

In the above code, the value from cell A1 assigns to the value returned by the input box that returns the value entered by the user.

3. From Another Cell

You can also set cell value using the value from another cell. Let’s say if you want to add value to cell A1 from the cell B1, the code would be:

Range("A1") = Range("B1").Value

You can also refer to cell B1 without using the value property.

Range("A1") = Range("B1")

4. Set Value in an Entire Range

Imagine you want to enter values in multiple cells or a range of cells instead of a single cell, in that case, you need to write code like the below:

Range("A1:A10").Value = Date
Range("B1, B10").Value = Now

In the first line of code, you have an entire range from cell A1 to A10, and in the second line, there are two cells B1 and B10.

Get Cell Value

As I said, you can use the same value property to get value from a cell.

1. Get Value from the ActiveCell

Let’s say you want to get the value from the active cell, in that case, you need to use the following code.

ActiveCell.Value = Range("A1")

In the above code, you have used the value property with the active cell and then assigned that value to cell A1.

2. Assign to a Variable

You can also get a value from a cell and further assign it to a variable.

Now in the above code, you have the variable “i” Which has the date as its data type. In the second line of the code, the value from cell A1 is assigned to the variable.

3.  Show in a MsgBox

Now imagine, you want to show the value from cell A1 using a message box. In this case, the code would be like the below.

MsgBox Range("A1").Value

In the above code, the message box will take value from cell A1 and show it to the user.

Change Cell Value

You can also make changes to a cell value, and here I have shared a few examples that can help you to understand this.

1. Add a Number to an Existing Number

Let’s say if you want to add one to the number that you have in cell A1, you can use the following code.

Range("A1").Value = Range("A1").Value + 1

The above code assigns value to cell A1 by taking value from cell A1 itself and adding one to it. But you can also use VBA IF THEN ELSE to write a condition to change only when there is a number in the cell.

If IsNumeric(Range("A1").Value) Then
  Range("A1").Value = Range("A1").Value + 1
End If

2. Remove First Character from Cell

Now, the following code removes the first character from the cell value and assigns the rest of the value back to the cell.

Range("A1").Value = Right(Range("A1").Value, Len(Range("A1").Value) - 1)

More Tutorials

    • Count Rows using VBA in Excel
    • Excel VBA Font (Color, Size, Type, and Bold)
    • Excel VBA Hide and Unhide a Column or a Row
    • Excel VBA Range – Working with Range and Cells in VBA
    • Apply Borders on a Cell using VBA in Excel
    • Find Last Row, Column, and Cell using VBA in Excel
    • Insert a Row using VBA in Excel
    • Merge Cells in Excel using a VBA Code
    • Select a Range/Cell using VBA in Excel
    • SELECT ALL the Cells in a Worksheet using a VBA Code
    • ActiveCell in VBA in Excel
    • Special Cells Method in VBA in Excel
    • UsedRange Property in VBA in Excel
    • VBA AutoFit (Rows, Column, or the Entire Worksheet)
    • VBA ClearContents (from a Cell, Range, or Entire Worksheet)
    • VBA Copy Range to Another Sheet + Workbook
    • VBA Enter Value in a Cell (Set, Get and Change)
    • VBA Insert Column (Single and Multiple)
    • VBA Named Range | (Static + from Selection + Dynamic)
    • VBA Range Offset
    • VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
    • VBA Wrap Text (Cell, Range, and Entire Worksheet)
    • VBA Check IF a Cell is Empty + Multiple Cells

    ⇠ Back to What is VBA in Excel

    Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes

    Quick Guide to String Functions

    String operations Function(s)
    Append two or more strings Format or «&»
    Build a string from an array Join
    Compare — normal StrComp or «=»
    Compare — pattern Like
    Convert to a string CStr, Str
    Convert string to date Simple: CDate
    Advanced: Format
    Convert string to number Simple: CLng, CInt, CDbl, Val
    Advanced: Format
    Convert to unicode, wide, narrow StrConv
    Convert to upper/lower case StrConv, UCase, LCase
    Extract part of a string Left, Right, Mid
    Format a string Format
    Find characters in a string InStr, InStrRev
    Generate a string String
    Get length of a string Len
    Remove blanks LTrim, RTrim, Trim
    Replace part of a string Replace
    Reverse a string StrReverse
    Parse string to array Split

    The Webinar

    If you are a member of the website, click on the image below to view the webinar for this post.

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

    vba strings video

    Introduction

    Using strings is a very important part of VBA. There are many types of manipulation you may wish to do with strings. These include tasks such as

    • extracting part of a string
    • comparing strings
    • converting numbers to a string
    • formatting a date to include weekday
    • finding a character in a string
    • removing blanks
    • parsing to an array
    • and so on

    The good news is that VBA contains plenty of functions to help you perform these tasks with ease.

    This post provides an in-depth guide to using string in VBA. It explains strings in simple terms with clear code examples. I have laid it out so the post can be easily used as a quick reference guide.

    If you are going to use strings a lot then I recommend you read the first section as it applies to a lot of the functions. Otherwise you can read in order or just go to the section you require.

    Read This First!

    The following two points are very important when dealing with VBA string functions.

    The Original String is not Changed

    An important point to remember is that the VBA string functions do not change the original string. They return a new string with the changes the function made. If you want to change the original string you simply assign the result to the original string. See the section Extracting Part of a String for examples of this.

    How To Use Compare

    Some of the string functions such as StrComp() and Instr() etc. have an optional Compare parameter. This works as follows:

    vbTextCompare: Upper and lower case are considered the same

    vbBinaryCompare: Upper and lower case are considered different

    The following code uses the string comparison function StrComp() to demonstrate the Compare parameter

    ' https://excelmacromastery.com/
    Sub Comp1()
    
        ' Prints 0  : Strings match
        Debug.Print StrComp("ABC", "abc", vbTextCompare)
        ' Prints -1 : Strings do not match
        Debug.Print StrComp("ABC", "abc", vbBinaryCompare)
    
    End Sub
    

    You can use the Option Compare setting instead of having to use this parameter each time. Option Compare is set at the top of a Module. Any function that uses the Compare parameter will take this setting as the default. The two ways to use Option Compare are:

    1. Option Compare Text: makes vbTextCompare the default Compare argument

    ' https://excelmacromastery.com/
    Option Compare Text
    
    Sub Comp2()
        ' Strings match - uses vbCompareText as Compare argument
        Debug.Print StrComp("ABC", "abc")
        Debug.Print StrComp("DEF", "def")
    End Sub
    

    2. Option Compare Binary: Makes vbBinaryCompare the default Compare argument

    ' https://excelmacromastery.com/
    Option Compare Binary
    
    Sub Comp2()
        ' Strings do not match - uses vbCompareBinary as Compare argument
        Debug.Print StrComp("ABC", "abc")
        Debug.Print StrComp("DEF", "def")
    End Sub
    

    If Option Compare is not used then the default is Option Compare Binary.

    Now that you understand these two important points about string we can go ahead and look at the string functions individually.

    Go back to menu

    Appending Strings

    VBA String Functions - Smaller

    ABC Cube Pile © Aleksandr Atkishkin | Dreamstime.com

    You can append strings using the & operator. The following code shows some examples of using it

    ' https://excelmacromastery.com/
    Sub Append()
    
        Debug.Print "ABC" & "DEF"
        Debug.Print "Jane" & " " & "Smith"
        Debug.Print "Long " & 22
        Debug.Print "Double " & 14.99
        Debug.Print "Date " & #12/12/2015#
    
    End Sub
    

    You can see in the example that different types such as dates and number are automatically converted to strings. You may see the + operator being used to append strings. The difference is that this operator will only work with string types. If you try to use it with other type you will get an error.

        ' This will give the error message:  "Type Mismatch"
        Debug.Print "Long " + 22
    

    If you want to do more complex appending of strings then you may wish to use the Format function described below.

    Go back to menu

    Extracting Part of a String

    The functions discussed in this section are useful when dealing with basic extracting from a string. For anything more complicated you might want to check out my post on How to Easily Extract From Any String Without Using VBA InStr.

    Function Parameters Description Example
    Left string, length Return chars from left side Left(«John Smith»,4)
    Right string, length Return chars from right side Right(«John Smith»,5)
    Mid string, start, length Return chars from middle Mid(«John Smith»,3,2)

    The Left, Right, and Mid functions are used to extract parts of a string. They are very simple functions to use. Left reads characters from the left, Right from the right and Mid from a starting point that you specify.

    ' https://excelmacromastery.com/
    Sub UseLeftRightMid()
    
        Dim sCustomer As String
        sCustomer = "John Thomas Smith"
    
        Debug.Print Left(sCustomer, 4)  '  Prints: John
        Debug.Print Right(sCustomer, 5) '  Prints: Smith
    
        Debug.Print Left(sCustomer, 11)  '  Prints: John Thomas
        Debug.Print Right(sCustomer, 12)  '  Prints: Thomas Smith
    
        Debug.Print Mid(sCustomer, 1, 4) ' Prints: John
        Debug.Print Mid(sCustomer, 6, 6) ' Prints: Thomas
        Debug.Print Mid(sCustomer, 13, 5) ' Prints: Smith
    
    End Sub
    

    As mentioned in the previous section, VBA string functions do not change the original string. Instead, they return the result as a new string.

    In the next example you can see that the string Fullname was not changed after using the Left function

    ' https://excelmacromastery.com/
    Sub UsingLeftExample()
    
        Dim Fullname As String
        Fullname = "John Smith"
    
        Debug.Print "Firstname is: "; Left(Fullname, 4)
        ' Original string has not changed
        Debug.Print "Fullname is: "; Fullname
    
     End Sub
    

    If you want to change the original string you simply assign it to the return value of the function

    ' https://excelmacromastery.com/
    Sub ChangingString()
    
        Dim name As String
        name = "John Smith"
    
        ' Assign return string to the name variable
        name = Left(name, 4)
    
        Debug.Print "Name is: "; name
    
     End Sub
    

    Go back to menu

    Searching Within a String

    Function Params Description Example
    InStr String1, String2 Finds position of string InStr(«John Smith»,»h»)
    InStrRev StringCheck, StringMatch Finds position of string from end InStrRev(«John Smith»,»h»)

    InStr and InStrRev are VBA functions used to search through strings for a substring. If the search string is found then the position(from the start of the check string) of the search string is returned. If the search string is not found then zero is returned. If either string is null then null is returned.

    InStr Description of Parameters

    InStr() Start[Optional], String1, String2, Compare[Optional]

    • Start As Long[Optional – Default is 1]: This is a number that specifies the starting search position from the left
    • String1 As String: The string to search
    • String2 As String: The string to search for
    • Compare As vbCompareMethod : See the section on Compare above for more details

    InStr Use and Examples

    InStr returns the first position in a string where a given substring is found. The following shows some examples of using it

    ' https://excelmacromastery.com/
    Sub FindSubString()
    
        Dim name As String
        name = "John Smith"
    
        ' Returns 3 - position of first h
        Debug.Print InStr(name, "h")
        ' Returns 10 - position of first h starting from position 4
        Debug.Print InStr(4, name, "h")
        ' Returns 8
        Debug.Print InStr(name, "it")
        ' Returns 6
        Debug.Print InStr(name, "Smith")
        ' Returns 0 - string "SSS" not found
        Debug.Print InStr(name, "SSS")
    
    End Sub
    

    InStrRev Description of Parameters

    InStrRev() StringCheck, StringMatch, Start[Optional], Compare[Optional]

    • StringCheck As String: The string to search
    • StringMatch: The string to search for
    • Start As Long[Optional – Default is -1]: This is a number that specifies the starting search position from the right
    • Compare As vbCompareMethod: See the section on Compare above for more details

    InStrRev Use and Examples

    The InStrRev function is the same as InStr except that it searches from the end of the string. It’s important to note that the position returned is the position from the start. Therefore if there is only one instance of the search item then both InStr() and InStrRev() will return the same value.

    The following code show some examples of using InStrRev

    ' https://excelmacromastery.com/
    Sub UsingInstrRev()
    
        Dim name As String
        name = "John Smith"
    
        ' Both Return 1 - position of the only J
        Debug.Print InStr(name, "J")
        Debug.Print InStrRev(name, "J")
    
        ' Returns 10 - second h
        Debug.Print InStrRev(name, "h")
        ' Returns 3 - first h as searches from position 9
        Debug.Print InStrRev(name, "h", 9)
    
        ' Returns 1
        Debug.Print InStrRev(name, "John")
    
    End Sub
    

    The InStr and InStrRev functions are useful when dealing with basic string searches. However, if you are going to use them for extracting text from a string they can make things complicated. I have written about a much better way to do this in my post How to Easily Extract From Any String Without Using VBA InStr.

    Go back to menu

    Removing Blanks

    Function Params Description Example
    LTrim string Removes spaces from left LTrim(» John «)
    RTrim string Removes spaces from right RTrim(» John «)
    Trim string Removes Spaces from left and right Trim(» John «)

    The Trim functions are simple functions that remove spaces from either the start or end of a string.

    Trim Functions Use and Examples

    • LTrim removes spaces from the left of a string
    • RTrim removes spaces from the right of a string
    • Trim removes spaces from the left and right of a string
    ' https://excelmacromastery.com/
    Sub TrimStr()
    
        Dim name As String
        name = "  John Smith  "
    
        ' Prints "John Smith  "
        Debug.Print LTrim(name)
        ' Prints "  John Smith"
        Debug.Print RTrim(name)
        ' Prints "John Smith"
        Debug.Print Trim(name)
    
    End Sub
    

    Go back to menu

    Length of a String

    Function Params Description Example
    Len string Returns length of string Len («John Smith»)

    Len is a simple function when used with a string. It simply returns the number of characters the string contains. If used with a numeric type such as long it will return the number of bytes.

    ' https://excelmacromastery.com/
    Sub GetLen()
    
        Dim name As String
        name = "John Smith"
    
        ' Prints 10
        Debug.Print Len("John Smith")
        ' Prints 3
        Debug.Print Len("ABC")
    
        ' Prints 4 as Long is 4 bytes in size
        Dim total As Long
        Debug.Print Len(total)
    
    End Sub
    

    Go back to menu

    Reversing a String

    Function Params Description Example
    StrReverse string Reverses a string StrReverse («John Smith»)

    StrReverse is another easy-to-use function. It simply returns the given string with the characters reversed.

    ' https://excelmacromastery.com/
    Sub RevStr()
    
        Dim s As String
        s = "Jane Smith"
        ' Prints: htimS enaJ
        Debug.Print StrReverse(s)
    
    End Sub
    

    Go back to menu

    Comparing Strings

    Function Params Description Example
    StrComp string1, string2 Compares 2 strings StrComp («John», «John»)

    The function StrComp is used to compare two strings. The following subsections describe how it is used.

    Description of Parameters

    StrComp()  String1, String2, Compare[Optional]

    • String1 As String: The first string to compare
    • String2 As String: The second string to compare
    • Compare As vbCompareMethod : See the section on Compare above for more details

    StrComp Return Values

    Return Value Description
    0 Strings match
    -1 string1 less than string2
    1 string1 greater than string2
    Null if either string is null

    Use and Examples

    The following are some examples of using the StrComp function

    ' https://excelmacromastery.com/
    Sub UsingStrComp()
    
       ' Returns 0
       Debug.Print StrComp("ABC", "ABC", vbTextCompare)
       ' Returns 1
       Debug.Print StrComp("ABCD", "ABC", vbTextCompare)
       ' Returns -1
       Debug.Print StrComp("ABC", "ABCD", vbTextCompare)
       ' Returns Null
       Debug.Print StrComp(Null, "ABCD", vbTextCompare)
    
    End Sub
    

    Compare Strings using Operators

    You can also use the equals sign to compare strings. The difference between the equals comparison and the StrComp function are:

    1. The equals sign returns only true or false.
    2. You cannot specify a Compare parameter using the equal sign – it uses the “Option Compare” setting.

    The following shows some examples of using equals to compare strings

    ' https://excelmacromastery.com/
    Option Compare Text
    
    Sub CompareUsingEquals()
    
        ' Returns true
        Debug.Print "ABC" = "ABC"
        ' Returns true because "Compare Text" is set above
        Debug.Print "ABC" = "abc"
        ' Returns false
        Debug.Print "ABCD" = "ABC"
        ' Returns false
        Debug.Print "ABC" = "ABCD"
        ' Returns null
        Debug.Print Null = "ABCD"
    
    End Sub
    

    The Operator “<>” means “does not equal”. It is essentially the opposite of using the equals sign as the following code shows

    ' https://excelmacromastery.com/
    Option Compare Text
    
    Sub CompareWithNotEqual()
    
        ' Returns false
        Debug.Print "ABC" <> "ABC"
        ' Returns false because "Compare Text" is set above
        Debug.Print "ABC" <> "abc"
        ' Returns true
        Debug.Print "ABCD" <> "ABC"
        ' Returns true
        Debug.Print "ABC" <> "ABCD"
        ' Returns null
        Debug.Print Null <> "ABCD"
    
    End Sub
    

    Go back to menu

    Comparing Strings using Pattern Matching

    Operator Params Description Example
    Like string, string pattern checks if string has the given pattern «abX» Like «??X»
    «54abc5» Like «*abc#»
    Token Meaning
    ? Any single char
    # Any single digit(0-9)
    * zero or more characters
    [charlist] Any char in the list
    [!charlist] Any char not in the char list

    Pattern matching is used to determine if a string has a particular pattern of characters. For example, you may want to check that a customer number has 3 digits followed by 3 alphabetic characters or a string has the letters XX followed by any number of characters.

    If the string matches the pattern then the return value is true, otherwise it is false.

    Pattern matching is similar to the VBA Format function in that there are almost infinite ways to use it. In this section I am going to give some examples that will explain how it works. This should cover the most common uses. If you need more information about pattern matching you can refer to the MSDN Page for the Like operator.

    Lets have a look at a basic example using the tokens. Take the following pattern string

    [abc][!def]?#X*

    Let’s look at how this string works
    [abc] a character that is either a,b or c
    [!def] a character that is not d,e or f
    ? any character
    # any digit
    X the character X
    * followed by zero or more characters

    Therefore the following string is valid
    apY6X

    a is one of abc
    p is not one of the characters d, e or f
    Y is any character
    6 is a digit
    X is the letter X

    The following code examples show the results of various strings with this pattern

    ' https://excelmacromastery.com/
    Sub Patterns()
    
        ' True
        Debug.Print 1; "apY6X" Like "[abc][!def]?#X*"
        ' True - any combination of chars after x is valid
        Debug.Print 2; "apY6Xsf34FAD" Like "[abc][!def]?#X*"
        ' False - char d not in [abc]
        Debug.Print 3; "dpY6X" Like "[abc][!def]?#X*"
        ' False - 2nd char e is in [def]
        Debug.Print 4; "aeY6X" Like "[abc][!def]?#X*"
        ' False - A at position 4 is not a digit
        Debug.Print 5; "apYAX" Like "[abc][!def]?#X*"
        ' False - char at position 5 must be X
        Debug.Print 6; "apY6Z" Like "[abc][!def]?#X*"
    
    End Sub
    

    Real-World Example of Pattern Matching

    To see a real-world example of using pattern matching check out Example 3: Check if a filename is valid.

    Important Note on VBA Pattern Matching

    The Like operator uses either Binary or Text comparison based on the Option Compare setting. Please see the section on Compare above for more details.

    Go back to menu

    Replace Part of a String

    Function Params Description Example
    Replace string, find, replace,
    start, count, compare
    Replaces a substring with a substring Replace («Jon»,»n»,»hn»)

    Replace is used to replace a substring in a string by another substring. It replaces all instances of the substring that are found by default.

    Replace Description of Parameters

    Replace()  Expression, Find, Replace, Start[Optional], Count[Optional], Compare[Optional]

    • Expression As String: The string to replace chars in
    • Find As String: The substring to replace in the Expression string
    • Replace As String: The string to replace the Find substring with
    • Start As Long[Optional – Default is 1]: The start position in the string
    • Count As Long[Optional – Default is -1]: The number of substitutions to make. The default -1 means all.
    • Compare As vbCompareMethod : See the section on Compare above for more details

    Use and Examples

    The following code shows some examples of using the Replace function

    ' https://excelmacromastery.com/
    Sub ReplaceExamples()
    
        ' Replaces all the question marks with(?) with semi colons(;)
        Debug.Print Replace("A?B?C?D?E", "?", ";")
        ' Replace Smith with Jones
        Debug.Print Replace("Peter Smith,Ann Smith", "Smith", "Jones")
        ' Replace AX with AB
        Debug.Print Replace("ACD AXC BAX", "AX", "AB")
    
    End Sub
    

    Output
    A;B;C;D;E
    Peter Jones,Sophia Jones
    ACD ABC BAB

    In the following examples we use the Count optional parameter. Count determines the number of substitutions to make. So for example, setting Count equal to one means that only the first occurrence will be replaced.

    ' https://excelmacromastery.com/
    Sub ReplaceCount()
    
        ' Replaces first question mark only
        Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=1)
        ' Replaces first three question marks
        Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=3)
    
    End Sub
    

    Output
    A;B?C?D?E
    A;B;C;D?E

    The Start optional parameter allow you to return part of a string. The position you specify using Start is where it starts returning the string from. It will not return any part of the string before this position whether a replace was made or not.

    ' https://excelmacromastery.com/
    Sub ReplacePartial()
    
        ' Use original string from position 4
        Debug.Print Replace("A?B?C?D?E", "?", ";", Start:=4)
        ' Use original string from position 8
        Debug.Print Replace("AA?B?C?D?E", "?", ";", Start:=8)
        ' No item replaced but still only returns last 2 characters
        Debug.Print Replace("ABCD", "X", "Y", Start:=3)
    
    End Sub
    

    Output
    ;C;D;E
    ;E
    CD

    Sometimes you may only want to replace only upper or lower case letters. You can use the Compare parameter to do this. This is used in a lot of string functions.  For more information on this check out the Compare section above.

    ' https://excelmacromastery.com/
    Sub ReplaceCase()
    
        ' Replace capital A's only
        Debug.Print Replace("AaAa", "A", "X", Compare:=vbBinaryCompare)
        ' Replace All A's
        Debug.Print Replace("AaAa", "A", "X", Compare:=vbTextCompare)
    
    End Sub
    

    Output
    XaXa
    XXXX

    Multiple Replaces

    If you want to replace multiple values in a string you can nest the calls. In the following code we want to replace X and Y with A and B respectively.

    ' https://excelmacromastery.com/
    Sub ReplaceMulti()
    
        Dim newString As String
    
        ' Replace A with X
        newString = Replace("ABCD ABDN", "A", "X")
        ' Now replace B with Y in new string
        newString = Replace(newString, "B", "Y")
    
        Debug.Print newString
    
    End Sub
    

    In the next example we will change the above code to perform the same task. We will use the return value of the first replace as the argument for the second replace.

    ' https://excelmacromastery.com/
    Sub ReplaceMultiNested()
    
        Dim newString As String
    
        ' Replace A with X and B with Y
        newString = Replace(Replace("ABCD ABDN", "A", "X"), "B", "Y")
    
        Debug.Print newString
    
    End Sub
    

    The result of both of these Subs is
    XYCD XYDN

    Go back to menu

    Convert Types to String(Basic)

    This section is about converting numbers to a string. A very important point here is that most the time VBA will automatically convert to a string for you. Let’s look at some examples

    ' https://excelmacromastery.com/
    Sub AutoConverts()
    
        Dim s As String
        ' Automatically converts number to string
        s = 12.99
        Debug.Print s
    
        ' Automatically converts multiple numbers to string
        s = "ABC" & 6 & 12.99
        Debug.Print s
    
        ' Automatically converts double variable to string
        Dim d As Double, l As Long
        d = 19.99
        l = 55
        s = "Values are " & d & " " & l
        Debug.Print s
    
    End Sub
    

    When you run the above code you can see that the number were automatically converted to strings. So when you assign a value to a string VBA will look after the conversion for you most of the time. There are conversion functions in VBA and in the following sub sections we will look at the reasons for using them.

    Explicit Conversion

    Function Params Description Example
    CStr expression Converts a number variable to a string CStr («45.78»)
    Str number Converts a number variable to a string Str («45.78»)

    In certain cases you may want to convert an item to a string without have to place it in a string variable first. In this case you can use the Str or CStr functions. Both take an  expression as a function and this can be any type such as long, double, data or boolean.

    Let’s look at a simple example. Imagine you are reading a list of values from different types of cells to a collection. You can use the Str/CStr functions to ensure they are all stored as strings. The following code shows an example of this

    ' https://excelmacromastery.com/
    Sub UseStr()
    
        Dim coll As New Collection
        Dim c As Range
    
        ' Read cell values to collection
        For Each c In Range("A1:A10")
            ' Use Str to convert cell value to a string
            coll.Add Str(c)
        Next
    
        ' Print out the collection values and type
        Dim i As Variant
        For Each i In coll
            Debug.Print i, TypeName(i)
        Next
    
    End Sub
    

    In the above example we use Str to convert the value of the cell to a string. The alternative to this would be to assign the value to a string and then assigning the string to the collection. So you can see that using Str here is much more efficient.

    Multi Region

    The difference between the Str and CStr functions is that CStr converts based on the region. If your macros will be used in multiple regions then you will need to use CStr for your string conversions.

    It is good to practise to use CStr when reading values from cells. If your code ends up being used in another region then you will not have to make any changes to make it work correctly.

    Go back to menu

    Convert String to Number- CLng, CDbl, Val etc.

    Function Returns Example
    CBool Boolean CBool(«True»), CBool(«0»)
    CCur Currency CCur(«245.567»)
    CDate Date CDate(«1/1/2017»)
    CDbl Double CCur(«245.567»)
    CDec Decimal CDec(«245.567»)
    CInt Integer CInt(«45»)
    CLng Long Integer CLng(«45.78»)
    CVar Variant CVar(«»)

    The above functions are used to convert strings to various types. If you are assigning to a variable of this type then VBA will do the conversion automatically.

    ' https://excelmacromastery.com/
    Sub StrToNumeric()
    
        Dim l As Long, d As Double, c As Currency
        Dim s As String
        s = "45.923239"
    
        l = s
        d = s
        c = s
    
        Debug.Print "Long is "; l
        Debug.Print "Double is "; d
        Debug.Print "Currency is "; c
    
    End Sub
    

    Using the conversion types gives more flexibility. It means you can determine the type at runtime. In the following code we set the type based on the sType argument passed to the PrintValue function. As this type can be read from an external source such as a cell, we can set the type at runtime. If we declare a variable as Long then it will always be long when the code runs.

    ' https://excelmacromastery.com/
    Sub Test()
        ' Prints  46
        PrintValue "45.56", "Long"
        ' Print 45.56
        PrintValue "45.56", ""
    End Sub
    
    Sub PrintValue(ByVal s As String, ByVal sType As String)
    
        Dim value
    
        ' Set the data type based on a type string
        If sType = "Long" Then
            value = CLng(s)
        Else
            value = CDbl(s)
        End If
        Debug.Print "Type is "; TypeName(value); value
    
    End Sub
    

    If a string is not a valid number(i.e. contains symbols other numeric) then you get a “Type Mismatch” error.

    ' https://excelmacromastery.com/
    Sub InvalidNumber()
    
        Dim l As Long
    
        ' Will give type mismatch error
        l = CLng("45A")
    
    End Sub
    

    The Val Function

    The value function convert numeric parts of a string to the correct number type.

    The Val function converts the first numbers it meets. Once it meets letters in a string it stops. If there are only letters then it returns zero as the value. The following code shows some examples of using Val

    ' https://excelmacromastery.com/
    Sub UseVal()
    
        ' Prints 45
        Debug.Print Val("45 New Street")
    
        ' Prints 45
        Debug.Print Val("    45 New Street")
    
        ' Prints 0
        Debug.Print Val("New Street 45")
    
        ' Prints 12
        Debug.Print Val("12 f 34")
    
    End Sub
    

    The Val function has two disadvantages

    1. Not Multi-Region – Val does not recognise international versions of numbers such as using commas instead of decimals. Therefore you should use the above conversion functions when you application will be used in multiple regions.

    2. Converts invalid strings to zero – This may be okay in some instances but in most cases it is better if an invalid string raises an error. The application is then aware there is a problem and can act accordingly. The conversion functions such as CLng will raise an error if the string contains non-numeric characters.

    Go back to menu

    Generate a String of items – String Function

    Function Params Description Example
    String number, character Converts a number variable to a string String (5,»*»)

    The String function is used to generate a string of repeated characters. The first argument is the number of times to repeat it, the second argument is the character.

    ' https://excelmacromastery.com/
    Sub GenString()
    
        ' Prints: AAAAA
        Debug.Print String(5, "A")
        ' Prints: >>>>>
        Debug.Print String(5, 62)
        ' Prints: (((ABC)))
        Debug.Print String(3, "(") & "ABC" & String(3, ")")
    
    End Sub
    

    Go back to menu

    Convert Case/Unicode – StrConv, UCase, LCase

    Function Params Description Example
    StrConv string, conversion, LCID Converts a String StrConv(«abc»,vbUpperCase)

    If you want to convert the case of a string to upper or lower you can use the UCase and LCase functions for upper and lower respectively. You can also use the StrConv function with the vbUpperCase or vbLowerCase argument. The following code shows example of using these three functions

    ' https://excelmacromastery.com/
    Sub ConvCase()
    
        Dim s As String
        s = "Mary had a little lamb"
    
        ' Upper
        Debug.Print UCase(s)
        Debug.Print StrConv(s, vbUpperCase)
    
        ' Lower
        Debug.Print LCase(s)
        Debug.Print StrConv(s, vbLowerCase)
    
        ' Sets the first letter of each word to upper case
        Debug.Print StrConv(s, vbProperCase)
    
    End Sub
    

    Output
    MARY HAD A LITTLE LAMB
    MARY HAD A LITTLE LAMB
    mary had a little lamb
    mary had a little lamb
    Mary Had A Little Lamb

    Other Conversions

    As well as case the StrConv can perform other conversions based on the Conversion parameter. The following table shows a list of the different parameter values and what they do. For more information on StrConv check out the MSDN Page.

    Constant Value Converts
    vbUpperCase 1 to upper case
    vbLowerCase 2 to lower case
    vbProperCase 3 first letter of each word to uppercase
    vbWide* 4 from Narrow to Wide
    vbNarrow* 8 from Wide to Narrow
    vbKatakana** 16 from Hiragana to Katakana
    vbHiragana 32 from Katakana to Hiragana
    vbUnicode 64 to unicode
    vbFromUnicode 128 from unicode

    Go back to menu

    Using Strings With Arrays

    Function Params Description Example
    Split expression, delimiter,
    limit, compare
    Parses a delimited string to an array arr = Split(«A;B;C»,»;»)
    Join source array, delimiter Converts a one dimensional array to a string s = Join(Arr, «;»)

    String to Array using Split

    You can easily parse a delimited string into an array. You simply use the Split function with the delimiter as parameter. The following code shows an example of using the Split function.

    ' https://excelmacromastery.com/
    Sub StrToArr()
    
        Dim arr() As String
        ' Parse string to array
        arr = Split("John,Jane,Paul,Sophie", ",")
    
        Dim name As Variant
        For Each name In arr
            Debug.Print name
        Next
    
    End Sub
    

    Output
    John
    Jane
    Paul
    Sophie

    You can find a complete guide to the split function here.

    Array to String using Join

    If you want to build a string from an array you can do so easily using the Join function. This is essentially a reverse of the Split function. The following code provides an example of using Join

    ' https://excelmacromastery.com/
    Sub ArrToStr()
    
        Dim Arr(0 To 3) As String
        Arr(0) = "John"
        Arr(1) = "Jane"
        Arr(2) = "Paul"
        Arr(3) = "Sophie"
    
        ' Build string from array
        Dim sNames As String
        sNames = Join(Arr, ",")
    
        Debug.Print sNames
    
    End Sub
    

    Output
    John,Jane,Paul,Sophie

    Go back to menu

    Formatting a String

    Function Params Description Example
    Format expression, format,
    firstdayofweek, firstweekofyear
    Formats a string Format(0.5, «0.00%»)

    The Format function is used to format a string based on given instructions. It is mostly used to place a date or number in certain format. The examples below show the most common ways you would format a date.

    ' https://excelmacromastery.com/
    Sub FormatDate()
    
        Dim s As String
        s = "31/12/2015 10:15:45"
    
        ' Prints: 31 12 15
        Debug.Print Format(s, "DD MM YY")
        ' Prints: Thu 31 Dec 2015
        Debug.Print Format(s, "DDD DD MMM YYYY")
        ' Prints: Thursday 31 December 2015
        Debug.Print Format(s, "DDDD DD MMMM YYYY")
        ' Prints: 10:15
        Debug.Print Format(s, "HH:MM")
        ' Prints: 10:15:45 AM
        Debug.Print Format(s, "HH:MM:SS AM/PM")
    
    End Sub
    

    The following examples are some common ways of formatting numbers

    ' https://excelmacromastery.com/
    Sub FormatNumbers()
    
        ' Prints: 50.00%
        Debug.Print Format(0.5, "0.00%")
        ' Prints: 023.45
        Debug.Print Format(23.45, "00#.00")
        ' Prints: 23,000
        Debug.Print Format(23000, "##,000")
        ' Prints: 023,000
        Debug.Print Format(23000, "0##,000")
        ' Prints: $23.99
        Debug.Print Format(23.99, "$#0.00")
    
    End Sub
    

    The Format function is quite a large topic and could use up a full post on it’s own. If you want more information then the MSDN Format Page provides a lot of information.

    Helpful Tip for Using Format

    A quick way to figure out the formatting to use is by using the cell formatting on an Excel worksheet. For example add a number to a cell. Then right click and format the cell the way you require. When you are happy with the format select Custom from the category listbox on the left.  When you select this you can see the format string in the type textbox(see image below). This is the string format you can use in VBA.

    VBA Format Function

    Format Cells Dialog

    Go back to menu

    Conclusion

    In almost any type of programming, you will spend a great deal of time manipulating strings. This post covers the many different ways you use strings in VBA.

    To get the most from use the table at the top to find the type of function you wish to use. Clicking on the left column of this function will bring you to that section.

    If you are new to strings in VBA, then I suggest you check out the Read this First section before using any of the functions.

    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.)

    Понравилась статья? Поделить с друзьями:
  • Set rulers in word
  • Set row height for all rows in excel
  • Set right to left in word
  • Set right margin in word
  • Set range name in excel