Excel vba оператор set

 

Доброго времени суток!  

  Прошу описать применение функцию «Set» на доступном языке :)  

  Особенно интересует когда обязательно объявлять:  
Set «Переменная» = Nothing  
а когда нет.  

  Спасибо заранее!  

  P.S. буду рад любому Вашему ответу, даже короткому ;)

 

Для переменных текстового, числового и логического типов SET не применяется.  
(применяется оператор LET, который можно не писать)  
Let a = «текст»: a=»текст2″: x = 5.25  

  Для ОБЪЕКТОВ необходимо использовать оператор SET  
set a = worksheets(1): set x = range(«a2:d4»)

 

KuklP

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

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

E-mail и реквизиты в профиле.

Всегда желательно в конце процедуры:  
Set «Переменная» = Nothing  
Это принудительно очистит память.

Я сам — дурнее всякого примера! …

 

И вообще, вас что, на Гугле забанили?  

  По VBA есть куча справочников — в каждом описано различие между SET и LET  

  Цитата:  

  В VBA существует два основных типа инструкций присваивания Let и  
Set. Инструкция Let используется в том случае, когда требуется присвоить  
значение выражения переменной или свойству. Её структура имеет следующий  
вид:  
      [Let] имя переменной = выражение
      Значение выражения может быть присвоено только в том случае, когда  
типы переменной и выражения совместимы. Например, нельзя присвоить  
строковой переменной значение выражения, являющегося числовым.  

        Инструкция Set присваивает ссылку на объект переменной или свойству  
объекта. При этом переменной присваивается выражение или значение,  
возвращаемое функцией. Структура инструкции Set имеет следующий вид:  
    Set переменная = [New] выражение | Nothing
    New — необязательный элемент. Это главное слово используется при  
описании для создания нового неявного экземпляра объекта. Если переменная  
содержит ссылку на объект, то при новом присвоении эта ссылка  
освобождается.  
    Выражение — обязательный элемент, представляющий выражение,  
состоящее из имени объекта, переменной соответствующего типа, функции  
или метода, которые возвращают объект того же типа.  
    Nothing — необязательный элемент, который разрывает связь элемента  
переменная с каким-либо определённым объектом. При этом переменная  
получает значение Nothing.

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

ИМХО, если переменная определена в процедуре (локальная), то время её жизни ограничено процедурой и по окончании процедуры (Exit Sub) все локальные переменные «умирают» и освобождают память. Поэтому Set «Переменная» = Nothing для локальных переменных делать не обязательно (конечно, если сама процедура не жутко жадная в смысле пожирания памяти)

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

The_Prist

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

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

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

{quote}{login=Alex_ST}{date=10.06.2010 11:29}{thema=}{post}Поэтому Set «Переменная» = Nothing для локальных переменных делать не обязательно (конечно, если сама процедура не жутко жадная в смысле пожирания памяти){/post}{/quote}Позвольте не согласиться. VBA редактор не такой уж продвинутый, как может показаться и он своими силами высвобождает память не всегда корректно. Он по идее должен все выгрузить, но такое происходит далеко не всегда. Лично я предпочитаю в большинстве случаев именно принудительно высвобождать память от подобных переменных, что и Вам советую.

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

 

KuklP

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

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

E-mail и реквизиты в профиле.

{quote}{login=Alex_ST}{date=10.06.2010 11:29}{thema=}{post}ИМХО, если переменная определена в процедуре (локальная), то время её жизни ограничено процедурой и по окончании процедуры (Exit Sub) все локальные переменные «умирают» и освобождают память. Поэтому Set «Переменная» = Nothing для локальных переменных делать не обязательно (конечно, если сама процедура не жутко жадная в смысле пожирания памяти){/post}{/quote}  
Алекс, я согласен с Вами, но считается хорошим тоном в прогаммировании такие переменные убивать после объявления.  
Это так же как с оператором Goto. Вроде и работает как надо, но не рекомендуют(и тон плохой). Сам никогда не использую:-) Если уж приспичило, то Gosub-Return. С уважением, Сергей.

Я сам — дурнее всякого примера! …

 

KuklP

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

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

E-mail и реквизиты в профиле.

Ну вот, за Димой разве успеешь…. Могу только дополнить — не только в ВБА. ВБ5, ВБ6 тоже грешили этим. И сами разработчики рекомендовали делать ТАК явно.

Я сам — дурнее всякого примера! …

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

По поводу «правил хорошего тона» при программировании абсолютно с вами согласен. Это как ржавчина на кузове автомобиля: на скорость не влияет, но и самому смотреть противно, и похвастаться перед другими как-то стыдно…  
Я сам всегда использую явное определение переменных через Dim (Option Explicit у меня ставится по умолчанию)и «убиение» по мере отпадания в них нужды переменных, установленных через Set.  
А уж про комментарии и говорить нечего! Без них и на свою-то программу через месяц будешь долго смотреть и «чесать репу» а что там, как и зачем? А уж про чужие программы и говорить нечего. Некоторые гуру форума, к сожалению иногда грешат примерами без комментариев. Я, если эти примеры кладу к себе в «копилку», то всегда прописываю в макросах что это за модуль, кем написан и откуда взят (ссылка на пост).

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

EducatedFool, спасибо Вам за ответы, но зачем иронизировать или Вы не заметили «…на доступном языке»?!  

  Спасибо Вам, Алексей, Дмитрий и Сергей!  

  P.S. теперь все понятно и просто.

 

KuklP

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

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

E-mail и реквизиты в профиле.

Алекс, я покраснел прочитав:  «к сожалению иногда грешат примерами без комментариев.» Правда, неудобно. Но я так и читаю чужой код. Не глядя на комменты. Самоучка — и так привык. С Вами абсолютно согласен(только вчера azam-у объяснял полезность комментов), но себя, боюсь, уже не исправлю:-( Я на этом форуме мнооооогому пытаюсь научиться. В первой строке списка доброта Юрий М, его умение общаться, не обижая других. Мне бы так. Ладно, что-то я совсем расчувствовался(это из мультика, не подумайте).

Я сам — дурнее всякого примера! …

 

слэн

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

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

зря вы на goto ополчились   :)  иногда без него никак..  

  коммменты, да, ленюсь писать, каюсь :)

 

The_Prist

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

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

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

Я тоже не понимаю, чем GoTo не угодил. Да, плохо смотрится, когда таких переходов куча и они используются нецелесообразно. Но иногда ведь действительно нужен этот переход и если без него, то наоборот, код смотрится более неграмотно и загроможденно, потому что приходится выдумать обходные пути. И не помню, чтобы кто-то рекомендовал его не использовать.  

  Вывод: не брезгуйте этим оператором — он бывает весьма полезен и не вреден в умеренных количествах.

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

 

The_Prist

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

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

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

Мне лично комменты писать откровенно лень. Прописывать комменты бывает намного дольше, чем сами коды. Для себя я пишу с комментами, а в форум — лень….  

  P.S. Исправляться не собираюсь. Пока, во всяком случае.

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

 

KuklP

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

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

E-mail и реквизиты в профиле.

{quote}{login=слэн}{date=10.06.2010 12:52}{thema=}{post}зря вы на goto ополчились   :)  иногда без него никак..  
коммменты, да, ленюсь писать, каюсь :){/post}{/quote}  
Хоть один случай бы увидеть, когда никак. Видимо я один понимаю вредность этого оператора.  
Ну —  

http://khpi-iip.mipk.kharkiv.edu/library/extent/dijkstra/pp/ewd215.html  

почитайте(прям сейчас нашел, не умею, как Дима, доходчиво объяснять)

Я сам — дурнее всякого примера! …

 

Hugo

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

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

Но что-то есть в этом GoTo… В AutoIt с 3-й версии его вообще убрали, тоже мучался, так я и не понял, как сподручнее обходить, местами вообще придуманный алгоритм менять приходилось…

 

KuklP

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

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

E-mail и реквизиты в профиле.

{quote}{login=Hugo}{date=10.06.2010 02:04}{thema=}{post}Но что-то есть в этом GoTo… В AutoIt с 3-й версии его вообще убрали, тоже мучался, так я и не понял, как сподручнее обходить, местами вообще придуманный алгоритм менять приходилось…{/post}{/quote}  
Вопрос структурирования прогаммы. А вообще-то я рад, что привлек к обсуждению таких уважаемых на форуме ребят. С вами уютно!

Я сам — дурнее всякого примера! …

 

слэн

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

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

вот пример когда никак:  

  on error goto    

    вот пример, когда как, но не красиво и yt’aatrnbdyj^  

    for i=1 to n  
for j=1 to m  
if a(i,j)=0 then goto ext  
next j  
next i  
ext:    

  можно, конечно, функцией оформить, с использованием exit function, но на вызов функции тратится время

 

{quote}{login=слэн}{date=10.06.2010 02:12}{thema=}{post}  
вот пример, когда как, но не красиво и yt’aatrnbdyj^{/post}{/quote}  
Согласен. Вот мой пример:  

http://forum.ixbt.com/topic.cgi?id=23:31044

 

KuklP

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

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

E-mail и реквизиты в профиле.

Слэн(хочу Вас все же называть с большой буквы), плохой пример. Во всех примерах мэтров программирования goto используется только для определения ошибки, с последующим Exit Sub. То есть goto на выход. И я в жизни не встречал ситуаций, когда нельзя было избежать его. Поначалу(это еще в 2000 где-то), напрягало, помню. Зато сейчас даже в мыслях не бывает. Вот так мозги перестроились. Прсто блок стоит.

Я сам — дурнее всякого примера! …

 

KuklP

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

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

E-mail и реквизиты в профиле.

{quote}{login=Казанский}{date=10.06.2010 02:17}{thema=Re: }{post}{quote}{login=слэн}{date=10.06.2010 02:12}{thema=}{post}  
вот пример, когда как, но не красиво и yt’aatrnbdyj^{/post}{/quote}  
Согласен. Вот мой пример:  

http://forum.ixbt.com/topic.cgi?id=23:31044

{/post}{/quote}  
Это пример, когда нельзя?  
Set s = Range(«a:a»).Find(«конь»)  
If Not s Is Nothing Then  
   If s.Offset(0, 1) = «белый» Then  
       answer = «YES»  
   Else  
       GoTo label1  
   End If  
Else  
label1:  
   answer = «NO»  
End If  
Как минимум две строки лишние и одной недостает(Set s = Nothing).

Я сам — дурнее всякого примера! …

 

слэн

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

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

вообщето алгоритм можно записать так:  

  Sub t()  
anser = «NO»  
Set s = Range(«a:a»).Find(«конь»)  
If s Is Nothing Then Exit Sub  
If s.Offset(0, 1) = «белый» Then answer = «YES»  
End Sub  

  что короче, яснее и быстрее  

    но я уже приводил на форуме множество раз алгоритмы, с использованием on error goto ( и в паре с ним ще и просто goto) — да, можно сделать по-другому, но так быстрее.. зачем же делать хуже, но без goto ?

 

слэн

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

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

можно еще так:  

  Sub t()  
on error goto ex  
anser = «NO»  
If Range(«a:a»).Find(«конь»).Offset(0, 1) = «белый» Then answer = «YES»  
ex:End Sub

 

KuklP

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

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

E-mail и реквизиты в профиле.

Слэн, Вы читаете, что я пишу?  
«Во всех примерах мэтров программирования goto используется только для определения ошибки, с последующим Exit Sub. То есть goto на выход.»  
И как мое утверждение конфликтует с Вашим: «on error goto»? :-)

Я сам — дурнее всякого примера! …

 

KuklP

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

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

E-mail и реквизиты в профиле.

В слове anser буква W пропущена, но это уже флуд. Если честно — боюсь, Диме позавчера спать не давали, оффтопили по полной. Чувствую, психанет и начнет стирать все без разбора. А главное по делу! Хотя этот топик флудом не считаю. Мы, как программеры, обсуждаем целесообразность применения оператора goto.

Я сам — дурнее всякого примера! …

 

Эммм…мммм…а хорошая тема получилось :)  

  Спасибо и за «GoTo» ;)

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

Ну, я бы не был так категоричен, утверждая, что обсуждение целесообразности применения оператора goto в топике с названием «Описание применения «Set»» не является оффтопом…  
Бедный топик-стартер уже давно наверное забросил читать эту тему ввиду распухания головы от развёрнутой здесь продвинутыми программистами дискуссии…

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

Да… А топик-стартер-то, оказывается, ещё не спит, а тему-то просматривает…

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

слэн

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

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

<но я уже приводил на форуме множество раз алгоритмы, с использованием on error goto ( и в паре с ним еще и просто goto)>  

  вот пример из моего решателя балды: (уж поверьте — оптимизировал-оптимизировал :) )  

  Sub fnd(ByVal s$)  
Dim lens&  
lens = Len(s)  
‘If lens < maxw Then Exit Sub  
Dim arr_r, pos&, n&, k&, sr$  
Dim s_n$, s_e$  
If s = «?êî» Then  
   pos = pos  
End If  
On Error Resume Next  

         pos = InStr(1, s, «?»)  
   s_n = Left(s, pos — 1)  
   s_e = Right(s, lens — pos)  
   ReDim arr_r(1 To 16)  
For k = 1 To 33  
   On Error GoTo er1  
   sr = s_n & arr_abc(k) & s_e  
   If cwt(sr) Then:  
   On Error GoTo n1  
   If chad(sr) = 0 Then GoTo nxt1  
n1: n = n + 1  
   If n > UBound(arr_r) Then ReDim Preserve arr_r(1 To n + 16)  
   arr_r(n) = sr  
   If n > UBound(arr_letter) Then ReDim Preserve arr_letter(1 To n + 99)  
   arr_letter(n) = arr_abc(k)  
   Resume nxt1  
er1: Resume nxt1  
nxt1: Next  
   sr = StrReverse(s)  
   pos = Len(s_e)  
   s_n = Left(sr, pos)  
   s_e = Right(sr, lens — pos — 1)  
On Error GoTo er2  
For k = 1 To 33  
   On Error GoTo er2  
   sr = s_n & arr_abc(k) & s_e  
   If cwt(sr) Then:  
   On Error GoTo n2  
   If chad(sr) = 0 Then GoTo nxt2  
n2:  n = n + 1  
   If n > UBound(arr_r) Then ReDim Preserve arr_r(1 To n + 16)  
   arr_r(n) = sr  
   If n > UBound(arr_letter) Then ReDim Preserve arr_letter(1 To n + 99)  
   arr_letter(n) = arr_abc(k)  
   Resume nxt2  
er2: Resume nxt2  
nxt2: Next  
If n = 0 Then Exit Sub  
‘If lens > maxw + 2 Then  
‘    maxw = lens — 2  
‘    k = 7  
‘    Cells(k, 1).Resize(n, 4).Insert Shift:=xlDown  
‘Else  
   k = Cells(Rows.Count, 1).End(xlUp).Row + 1  
‘End If  
Application.EnableEvents = False  
Cells(k, 1).Resize(n) = Application.Transpose(arr_r)  
Cells(k, 3).Resize(n) = Cells(i, j).Address(0, 0)  
Cells(k, 2).Resize(n) = lens  
Cells(k, 4).Resize(n) = Application.Transpose(arr_letter)  
Application.EnableEvents = True  
numn = numn + n  
numv = numv + 66  
End Sub

 

KuklP

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

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

E-mail и реквизиты в профиле.

#30

10.06.2010 15:37:39

To Alex_ST: Ну вот. пришел поручик Ржевский и все опошлил:-)  
При чем тут топикстартер… Я не понимаю:-)

Я сам — дурнее всякого примера! …

VBA Set

Excel VBA Set

“Set”, is a keyword used in VBA programming to assign a reference to an object or cell range which is going to remain fix throughout the program or code in Excel. VBA Set basically helps us in avoiding repetitive input of range we need to select while executing the code. In excel, “Set” is mostly applied on worksheets/cell range in a particular sheet.

Syntax

Set object-name/variable = Object/Range

Note: You need to have Developer tab in the excel worksheet.

If you do not see the “Developer” tab in excel, refer below steps:

Step 1: Click on File Option.

VBA Set Step 1

Step 2: Drop-down appears, Click on Options tab.

VBA Set Step 2

Step 3: Once you click on “Options”, a dialog box appears as shown below and click on the Customize Ribbon option.

VBA Set Step 3

Step 4: When we drag down in the customize ribbon options we will find an option for Developer we need to check that box which will enable us to use VBA in excel.

VBA Set Step 4

How to Use a Set Keyword in VBA?

Below are the different examples to use set keyword in Excel VBA.

You can download this VBA Set Excel Template here – VBA Set Excel Template

Excel VBA Set – Example #1

We shall take a simple example of a Set keyword in Excel VBA. Suppose we would like to select a range and set it as fix range so as to avoid the repetition. Below is the cell range containing the names:

vba Set Example 1-1

Follow the below steps to use set keyword in Excel VBA:

Step 1: Click on “Developer” tab and then click on the “Visual Basic” option on the left-hand side (first option) as shown below.

VBA Set Example 1-2

Once you click on it, a new window appears as shown below:

VBA Set Example 1-3

You will notice that it contains two tabs on the left-hand side, “Sheet1(Sheet1)” and “ThisWorkbook”. The only difference is “Sheet1” when you want to execute code for this particular sheet only and in “ThisWorkbook”, we can write a code and execute which can be applied for the whole excel workbook.

Step 2: Double Click on “Sheet1(Sheet1) and you will see a blank screen where we need to write the code. First, declare a subset as Sub name and press enter and you will see a subset created as shown below:

Code:

Sub setexmp()

End Sub

VBA Set Example 1-4

This is the way we create a subset and automatically “End Sub” appears. This is by default feature of excel. If “End Sub” does not appear the code will not execute and throw an error.

Step 3: Now, we shall declare variables to be used in the code.

Type Dim variable name and variable type. Here, the name will be like the identity of the range and type would be whether as Integer, Long, String, Range, etc.

Code:

Sub setexmp()

Dim Rnst As Range

End Sub

VBA Set Example 1-5

Here “Rnst” is a variable name and assign(As) it as Range function. This will alert the system that, a range selection would be done.

Step 4: Then type “Set” keyword and give a range using the format: Set variable = Range(“cell range”).

Code:

Sub setexmp()

Dim Rnst As Range
Set Rnst = Range("A2:A11")

End Sub

VBA Set Example 1-6

Step 5: We have to select this row range specified. Hence, type select as Rnst.Select Refer screenshot below:

Code:

Sub setexmp()

Dim Rnst As Range
Set Rnst = Range("A2:A11")
Rnst.Select

End Sub

VBA Set Example 1-7

Step 6: Run the code by hitting F5 or Run button and see the output.

VBA Set Example 1-8

It will select the Range specified which is from cells A2 to A11.

Excel VBA Set – Example #2

Suppose we want to paste these cells or range in another cell. We shall use the same code as above and add code for pasting that data in multiple columns.

Follow the below steps:

Step 1: Now we will copy the range of cells which is the name column. Type copy i.e. “Rnst.Copy”, when you type “Rnst.”a kind of drop-down appears. It contains various functions like copy, paste, etc.

VBA Set Example 2-1

Step 2: You can scroll down and select the desired function you want to perform. Here just type “Copy” as shown in the screenshot below:

Code:

Sub setexmp()

Dim Rnst As Range
Set Rnst = Range("A2:A11")
Rnst.Select
Rnst.Copy

End Sub

Copy Command Example 2-2

Step 3: Compile the code by pressing F8 Key.

VBA Set Example 2-3

Once, you execute this copy function, you will see that in excel the range is copied and dotted lines appear around the cell range as shown below:

Step 4: Now, we need to paste this cells, say in adjacent columns one by one, so we need to use a loop function “For” and suppose 5 times we need to paste so we will type it as shown below:

For Integer i = 1 to 5 -> this specifies how many times we need to paste the data. If 5 then 1 to 5 else whichever count you prefer.

Code:

Sub setexmp()

Dim Rnst As Range
Set Rnst = Range("A2:A11")
Rnst.Select
Rnst.Copy
For i = 1 To 5

End Sub

VBA Set Example 2-4

Step 5: Select a cell in which you want to paste this cell range. Suppose we want to start pasting from column B2 and then pasting the data should be dynamic i.e. it should automatically select adjacent columns one by one without overlapping. Hence, the syntax would be “Cell(row number, column number).PasteSpecial”.

Cells(2, i + 1).PasteSpecial, Here, 2-> represents the row number and, i+1 -> represents column number. i+1 means the first value of I declared in “For” loop is i=1, hence column value will become 2, it specifies that it start pasting from column B. And as and when i value increases it will keep selecting adjacent columns one by one.

Code:

Sub setexmp()

Dim Rnst As Range
Set Rnst = Range("A2:A11")
Rnst.Select
Rnst.Copy
For i = 1 To 5
  Cells(2, i + 1).PasteSpecial xlValues

End Sub

 PasteSpecial Command Example 2-5

Step 6: Type “Next i” which means that you are increasing the value of “i” one by one so that the column pasting remains dynamic.

Code:

Sub setexmp()

Dim Rnst As Range
Set Rnst = Range("A2:A11")
Rnst.Select
Rnst.Copy
For i = 1 To 5
  Cells(2, i + 1).PasteSpecial xlValues
Next i

End Sub

VBA Set Example 2-6

Step 7: Press “F8” to see the code execute line by line and will show you the pasting of cell in adjacent columns one by one.

VBA Set Example 2-7

Here you can see the value of i is 1 and data has been pasted in column B as desired.

Step 8: Now when you press “F8” again you will see that now the value of i is 2. Hence, 2+1 will become 3 and data will be pasted in Cell (2,3) i.e. row value is same but column number changes as shown in the screenshot below:

VBA Set Example 2-8

After repeating loop completes you will see the data pasted 5 times i.e. from count 1 to 5 starting to paste from Column B till Column F as shown below:

VBA Set Example 2-9

Excel VBA Set – Example #3

Suppose we would like to show a count of the number of cells in that range in a message box appearing on click of a button. We shall take the same data as shown below.

VBA Set Example 3-1

Also, we will run this example’s code in the new sheet. Hence, add a new sheet and in VBA window it will appear as below:

Add new sheet Example 3-2

We will have to insert a command button option. It’s a feature of excel, so follow the below steps:

Step 1: Enter a subset name say “Setcount()” as shown in the screenshot below:

Code:

Sub Setcount()

End Sub

VBA Set Example 3-3

Step 2: Declare the same variable “Rnct” as a range in the subset as shown in the screenshot below:

Code:

Sub Setcount()

Dim Rnct As Range

End Sub

Declare Variable Example 3-4

Step 3: Then type “Set” keyword and give a range.

Code:

Sub Setcount()

Dim Rnct As Range
Set Rnct = Range("A2:A11")

End Sub

VBA Set Example 3-5

Step 4: Now, after fixing the range, we need to see pop up box or dialog box showing the count of cells in the range. Hence, use “MsgBox” function which upon execution a count will appear in the dialog box. Type “MsgBox variable name.count”. The moment after typing the variable name then dot(.) a drop-down appears containing various functions and we would select “count” or manually type “count”.

VBA Set Example 3-6

Type “MsgBox Rnct.count” and upon execution, it will appear count.

Step 5: Now, we want to insert a command button and on click, on that button that message box should appear.

Click on “Insert” in the “Developer” tab as highlighted in the red box and you will see a drop-down of category “Form Controls”. Click on the very first rectangle box-like shape which we will have to manually draw and insert in excel sheet:

Insert Command button Example 3-7

Step 6: Upon click on the rectangle box, draw and insert the box in sheet and once you start drawing a dialog box appears as shown below. It’s an “Assign Macro” window button and select the “Setcount” subset macro. Click on “OK”.

Assign Macro Example 3-8

This signifies that we have assigned count macro to this button. And upon click, it will execute.

Step 7: It will appear as shown below in excel.

Button 2 Example 3-9

Step 8: Right-click on it and rename it using the “Edit Text” option as shown below:

Edit Text option Example 3-10

Step 9: Give it a name as “COUNT” and you will see it in excel as count as shown below.

Count Button Example 3-11

Step 10: Then click on the “COUNT” button: Once you click on “COUNT” button a message box appears as shown below:

VBA Set Example 3-12

As we can see there are 10 names and have shown the correct number from range A2 to A11.

Things to Remember

  • Make sure you have the “Developer” tab inserted in Excel ribbons to run this VBA codes.
  • ‘Set’ is mostly applied on worksheets/cell range in a particular sheet.

Recommended Articles

This is a guide to VBA Set. Here we discuss how to assign a reference to an object or cell range using excel VBA Set Keyword along with practical examples and downloadable excel template. Below are some useful excel articles related to VBA –

  1. VBA Concatenate
  2. VBA Range Cells
  3. VBA RGB
  4. VBA XML

VBA Set is a statement that assigns any value key that says an object or a reference to a variable. We use this function to define the parameter for a certain variable. For example, if we write Set M = A, the M reference has the same values and attributes as A.

In VBA, an object is a core of Excel because, without objects, we cannot do anything. Objects are a workbook, worksheet, and range. When we declare a variable, we need to assign a data type. We can also assign objects as data types. To assign a value to declared object variables, we need to use the word “SET.” The word “Set” refers to a new object in VBA. For example, the particular range of the particular worksheet.

Table of contents
  • Excel VBA Set Statement
    • How to use Excel VBA Set Statement?
      • #1 – Set Statement with Range Object Variables
      • #2 – Set Statement with Worksheet Object Variables
        • #1 – Without “Set” Word
        • #2 – With “Set” Word
      • #3 – Set Statement with Workbook Object Variables
    • Recommended Articles

VBA Set Statement

How to use Excel VBA Set Statement?

You can download this VBA Set Statement Template here – VBA Set Statement Template

#1 – Set Statement with Range Object Variables

For example, assume you want to use the range A1 to D5 quite often. Then, instead of writing the code as Range(“A1:D5”) every time, we can declare the variable as range and set the range reference as Range(“A1:D5”).

Step 1: Declare the variable as a Range object.

Code:

Sub Set_Example()

Dim MyRange As Range

End Sub

VBA Set Example 1

Step 2: When we assign the data type as a range, use the word “Set.”

Code:

Sub Set_Example()

Dim MyRange As Range

Set MyRange =

End Sub

VBA Set Example 1-1

Step 3: Now, mention the range.

Code:

Sub Set_Example()

  Dim MyRange As Range

  Set MyRange = Range("A1:D5")

End Sub

VBA Set Example 1-2

Step 4: The variable “MyRange” equals the range A1 to D5. Using this variable, we can access this range’s properties and methods.

VBA Set Example 1-3

We can copy, add a comment in excelIn Excel, Insert Comment is a feature used to share tips or details with different users working within the same spreadsheet. You can either right-click on the required cell, click on “Insert Comment” & type the comment, use the shortcut key, i.e., Shift+F2, or click on the Review Tab & select “New Comment”. read more, and do many other things.

For example, for purpose, we have created some numbers here.

VBA Set Example 1-4

Now using the variable, we will change the font size to 12.

Code:

Sub Set_Example()

  Dim MyRange As Range

  Set MyRange = Range("A1:D5")

  MyRange.Font.Size = 12

End Sub

VBA Set Example 1-5

It will change the font size of the assigned range.

VBA Set Example 1-6

Like this, we can do many things with a particular range by using the word “Set.”

#2 – Set Statement with Worksheet Object Variables

We have seen how “set” works with a range object in VBARange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more. It works the same as the worksheet object as well..

Let’s say you have 5 worksheets in your workbook. However, you want to keep going back to the one particular worksheet. So, you can set that worksheet name to the defined object variable.

For example, look at the below code.

Code:

Sub Set_Worksheet_Example()

    Dim Ws As Worksheet

    Set Ws = Worksheets("Summary Sheet")

End Sub

Visual basic Application Example 2

The above code defines the variable “Ws” as an object variable. In the next line, by using the word “Set,” we set the variable to the worksheet named “Summary Sheet.”

By using this variable, we can do all the associated things. Take a look at the below two sets of code.

#1 – Without “Set” Word

Code:

Sub Set_Worksheet_Example1()

    'To select the sheet
    Worksheets("Summary Sheet").Select

    'To Activate the sheet
    Worksheets("Summary Sheet").Activate

    'To hide the sheet
    Worksheets("Summary Sheet").Visible = xlVeryHidden

    'To unhide the sheet
    Worksheets("Summary Sheet").Visible = xlVisible

End Sub

Visual basic Application Example 2-1

Every time we have used the worksheets object to refer to the sheet “Summary Sheet,” This makes the code lengthy and requires a lot of time to type.

As part of the huge code, it is frustrating to type the worksheet name like this every time you need to reference it.

Now, look at the advantage of using “Set” in code.

#2 – With “Set” Word

Code:

Sub Set_Worksheet_Example()

    Dim Ws As Worksheet

    Set Ws = Worksheets("Summary Sheet")

   'To select the sheet
    Ws.Select

   'To Activate the sheet
    Ws.Activate

   'To hide the sheet
    Ws.Visible = xlVeryHidden

   'To unhide the sheet
    Ws.Visible = xlVisible

End Sub

Visual basic Appplication Example 2-2

When we set the worksheet name, we can see the variable name while entering the code as part of the list.

#3 – Set Statement with Workbook Object Variables

The real advantage of the word “Set” in VBA arises when we need to reference different workbooks.

When we work with different workbooks, it is hard to type in the full name of the workbook, along with its file extension.

Assume you have two different workbooks named “Sales Summary File 2018.xlsx” and “Sales Summary File 2019.xlsx” we can set the two workbooks like the below code.

Code:

Sub Set_Workbook_Example1()

Dim Wb1 As Workbook
Dim Wb2 As Workbook

Set Wb1 = Workbooks("Sales Summary File 2018.xlsx")
Set Wb2 = Workbooks("Sales Summary File 2019.xlsx")

End Sub

workbook object variables

Now, variable Wb1 is equal to the workbook named “Sales Summary File 2018.xlsx,” and variable Wb2 is equal to the workbook named “Sales Summary File 2019.xlsx”.

We can access all the properties and methods associated with the workbook using this variable.

We can shorten the code like the one below.

Without Using Set Keyword to activate the workbook:

Workbooks("Sales Summary File 2018.xlsx").Activate

Using the Set Keyword to activate the workbook:

Wb1.Activate

It makes the writing of the code much simpler. However, once we set the workbook name, there is a worry of typo errors in the workbook names.

Recommended Articles

This article is a guide to VBA Set. Here, we learn how to use Excel VBA set statements to reference the object variable and some simple to advanced examples. Below are some useful Excel articles related to VBA: –

  • VBA ReDim Array
  • VBA LEN
  • VBA Code in Excel
  • VBA RGB

Before we get into the Set keyword, I’m going to quickly go over a couple fundamentals about objects in VBA. If you already know this stuff, just skip ahead a couple sections.

Introduction to Objects

An object in a programming language is a class with some properties and methods. For example, a textbox is an object. This object can have properties like: 

  1. font color
  2. size 
  3. background color
  4. font styles like bold, italics and underline, etc. 

It can have methods like: 

  1. onchange 
  2. onclick 
  3. onload, etc.

An object is a data type that can hold values, properties, and change behavior too. In simple terms, we can also call an object a collection of several variables. In that respect, arrays, dictionaries, and lists are all objects, because they hold several values.

Assigning a Value to an Object

Unlike variables, objects cannot be assigned references using a mere “=” (equal to) sign. They are special since they hold several / large values.

The Set Keyword

The “set” keyword must be used in order to assign object references to any variable or empty the contents of an object.

Syntax

Set < object var > = {[ New ] < object expression >} | Nothing 

Where 

  1. < object var > is the name of the variable which will hold the object
  2. New is an optional keyword that can be used during declaration to implicitly enable object creation
  3. < object expression > is the expression that points to the object
  4. Nothing is used to empty the space the object is using and make is equal to null. “Nothing” is the keyword that has to be used for objects. This statement discontinues the association of the object with its variable name.

Examples

An Object for a Range in a Worksheet

Here we use the Set keyword to define a range of cells on a worksheet.

I = 5
J = 10
Set range_new1 = Worksheets("My demo sheet").Rows( i &amp;amp;amp; ":" &amp;amp;amp; j )

Open a Browser (Ex: Internet Explorer)

We create an object that defines a browser (in this case, Internet Explorer). From there onwards, we can easily refer to the same object or work on it using a single word.

Set IE_demo = CreateObject("InternetExplorer.Application")
    IE_demo.Visible = True

    IE_demo.Navigate "https://www.google.com"

The code below is a simple example to perform some actions on a browser window. We define an object that holds the document, i.e. all html code of the specific browser window. Then, using that object, we try to list out objects with the same tagname or classname or specific elements (as defined in the html content of the doc object).

' this line of code sets the “doc” as an object containing the browser’s document content
Set doc = IE_demo.document

Set the value for object “inputtags” . It is set to contain all input tags of the doc object.

Set inputtags = doc.getElementsByTagName("input").Value

Here the “elem” object is set to contain all element(s) of the document object that have the class name “all-title”. Then we click on the first item ( with index 0) in that list.

Set elem = doc.getElementsByClassName("all-title").Item
' now the first item in the list of elem object list is clicked
elem.all.Item(0).Click   
' close the document
doc.close
' empty the doc object and release resources
Set doc = Nothing

Setting a File as an Object

There may be situations where we keep referring to a file to perform many actions on it like open, read, write, append, validate, close, open file again, save data, and many more. Instead of referring to the whole file path again and again, it can instead be defined as an object with a short object name that can be used throughout the code. Here is an example that demonstrates this:

Set elem=doc.getElementsByClassName("all-title").Item
' now the first item in the list of elem object is clicked
elem.all.Item(0).Click
' close the document
doc.close
'empty the doc object and release resources
Set doc = Nothing

Example of how to set a file as an object in VBA

Sub open_a_file_demo()

' declare variables
Dim str_path_name
Dim wb1 As Workbook

' assigning a value
str_path_name = "C:UsersLAKSHMI RAMAKRISHNANDownloadsProject 2.xlsx"

' now let us open the file using the this statement and assign it to the wb1 object so that it can be used in the code further. The set keyword is used to do this.
Set wb1 = Workbooks.Open(Filename:=str_path_name, ReadOnly:=True)
‘Try reading the file using the object
Msgbox wb1.Sheets(2).cells(3, 4).Value
' Try writing after opening the file in "read only mode". This should throw an error.
Wb1.Sheets(0).Cells(2, 2).Value = "Try writing"
End Sub

Using Set Keyword to Create a Shell Object

There are several operations that use the shell commands to perform some things on the windows. For example, killing a task from the task manager, opening a file, running a thread at a scheduled time, and many more. 

Here is a short program to create the necessary variables and objects, as well to open a notepad and a browser window using the created shell object. The id of the object opened last is also printed at the end.

Sub shell_demo_4()

'Declaration of objects and variables
Dim objsh_obj As Object
Dim intcounter As Integer
Dim str_ie_pr_id

'Assign all values
Set str_ie_pr_id = Nothing
intcounter = 0
Set objsh_obj = CreateObject("shell.application")
counter = objsh_obj.Windows.Count

' open an internet explorer
IE = Shell("C:Program FilesInternet Exploreriexplore.exe -nosessionmerging , -noframemerging", vbNormalFocus)

'open a notepad
ret_val = Shell("C:WINDOWSNOTEPAD.EXE", 1)

'wait till the window opens
Do Until objsh_obj.Windows.Count = intcounter + 1
Loop

'set the new process ids for the opened objects

' the last but first that was opened
Set str_ie_pr_id = objsh_obj.Windows(objsh_obj.Windows.Count - 2)

' the last object that was opened
Set str_ie_pr_id = objsh_obj.Windows(objsh_obj.Windows.Count - 1)

'Print the last process id alone
Debug.Print str_ie_pr_id

End Sub 

Example of how to set a keyword to create a shell object in VBA

Conclusion

The above examples demonstrate the use of the “Set” keyword. We can create “short word” references to any object that can be easily referred to or reused in the code window further. It can help us avoid repeated use of lengthy expressions which might also be cumbersome and difficult to maintain.

Знак присвоения без SET присваивает скалярное значение. А с SET — ссылку на объект. То есть использовать его или нет — зависит от типа значения справа от знака присвоения. Ну и желаемого результата, конечно (включая и желание не получить ошибку несоответствия типов).

Пример.

  • Откройте Excel.
  • Откройте окно редактора VBA (Ctrl-F11). Измените размеры окон так, чтобы видеть и таблицу, и редактор.
  • В редакторе добавьте модуль (Insert-Module).
  • Вставьте в модуль следующий текст:
    Sub test()
    Dim x, y
    Range("A1").Value = 123
    x = Range("A1")
    Set y = Range("A1")
    End Sub

  • Поставьте курсор в середину модуля, и начните пошаговое выполнение нажатием F8. Доведите исполнение до финального End Sub (когда эта строка будет подсвечена жёлтым цветом).
  • Откройте окно локальных переменных (View — Locals Window).

Вы увидите, что первый оператор присвоения присвоил переменной x скалярное значение. Поскольку справа был объект, то в качестве скалярного значения было взято свойство объекта по умолчанию. Для объекта типа Range объектом по умолчанию является его свойство .Value — посему в переменную помещено значение 123. И соответственно переменная имеет тип Variant/Double.

А вот второй оператор присвоения, использующий Set, поместил во вторую переменную y ссылку на объект Range. И переменная имеет тип Variant/Object/Range.

Понравилась статья? Поделить с друзьями:
  • Excel vba не выдавать ошибку
  • Excel vba оператор select case
  • Excel vba не виден лист
  • Excel vba оператор do while
  • Excel vba начало программирования