Set vba excel что это

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

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Set Statement (wallstreetmojo.com)

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

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

Hopefully an easy question, but I’d quite like a technical answer to this!

What’s the difference between:

i = 4

and

Set i = 4

in VBA? I know that the latter will throw an error, but I don’t fully understand why.

ZygD's user avatar

ZygD

21k39 gold badges77 silver badges98 bronze badges

asked Dec 8, 2008 at 13:54

Jon Artus's user avatar

1

set is used to assign a reference to an object. The C equivalent would be

 int i;
int* ref_i;

i = 4; // Assigning a value (in VBA: i = 4)
ref_i = &i; //assigning a reference (in VBA: set ref_i = i)

TylerH's user avatar

TylerH

20.6k64 gold badges76 silver badges97 bronze badges

answered Dec 8, 2008 at 14:00

Treb's user avatar

TrebTreb

19.8k6 gold badges53 silver badges85 bronze badges

5

In your case, it will produce an error. :-)

Set assigns an object reference. For all other assignments the (implicit, optional, and little-used) Let statement is correct:

Set object = New SomeObject
Set object = FunctionReturningAnObjectRef(SomeArgument)

Let i = 0
Let i = FunctionReturningAValue(SomeArgument)

' or, more commonly '

i = 0
i = FunctionReturningAValue(SomeArgument)

answered Dec 8, 2008 at 13:57

Tomalak's user avatar

TomalakTomalak

330k66 gold badges523 silver badges623 bronze badges

From MSDN:

Set Keyword: In VBA, the Set keyword
is necessary to distinguish between
assignment of an object and assignment
of the default property of the object.
Since default properties are not
supported in Visual Basic .NET, the
Set keyword is not needed and is no
longer supported.

answered Dec 8, 2008 at 13:58

Galwegian's user avatar

GalwegianGalwegian

41.4k16 gold badges111 silver badges158 bronze badges

6

Set is used for setting object references, as opposed to assigning a value.

answered Dec 8, 2008 at 13:57

LeppyR64's user avatar

LeppyR64LeppyR64

5,2022 gold badges29 silver badges34 bronze badges

Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it’s doing an AddRef() call on the object to manage it’s lifetime.

answered Dec 8, 2008 at 13:59

Sean's user avatar

SeanSean

60.5k11 gold badges97 silver badges134 bronze badges

1

So when you want to set a value, you don’t need «Set»; otherwise, if you are referring to an object, e.g. worksheet/range etc., you need using «Set».

answered Sep 5, 2014 at 7:37

Eric Wang's user avatar

Eric WangEric Wang

9491 gold badge8 silver badges16 bronze badges

Set is an Keyword and it is used to assign a reference to an Object in VBA.

For E.g.,
*Below example shows how to use of Set in VBA.

Dim WS As Worksheet

Set WS = ActiveWorkbook.Worksheets(«Sheet1»)

WS.Name = «Amit»

answered Nov 11, 2013 at 5:05

Amit Singh's user avatar

Return to VBA Code Examples

In this Article

  • Defining Object Variables
  • Declaring the Object Variable
  • Set Value
  • Object Examples in Excel
    • Workbook Object
    • Worksheet Object
    • Range Object
    • Shape Object

This tutorial will teach you how to define object variables using the Set statement in VBA.

Defining Object Variables

Objects are the cornerstone of Microsoft Office – without objects, we cannot achieve anything.  In Excel, objects include the Workbook, Worksheet or Range Objects. In Microsoft Word, examples are the Document or Table object. Each object has a variety of Properties and Methods that can be programmed to control the behavior of that object.

Declaring the Object Variable

Before we can reference the object in code, and therefore control the object, we need to declare the object. We can do this using the Dim Statement.

Dim wkb as Workbook
Dim wks as Worksheet
Dim Rng as Range
Dim wdDoc as Document
Dim wdTbl as Table
Dim shp as Shape

This Dim declaration can occur inside a procedure:

vba objects 1

or outside a procedure at the module-level:

vba objects 2

If the variable is declared at the module-level (outside the procedure), the variable can be used throughout the module.

If the object variable is declared with the Public statement then the variable can be used throughout the VBA Project:

vba objects 3

Set Value

Once you have declared the object, you need to assign a value to the object. This must be done using the Set statement and can only be done within a Procedure.

Sub SetObjects()
   Set wkb = ActiveWorkbook
   Set wks = Sheet1
   Set rng = Range("A1:G4")
End Sub

Note: This is different than assigning values to non-object variables. You MUST use the Set statement to assign the object to the variable. If you do not, you’ll receive an error:

vba objects error

Once you have assigned a value to the object, you can then write code to control the behavior or manipulate the object.

Object Examples in Excel

Workbook Object

Once you have declared a workbook variable, you can then assign a workbook to that object and use the Properties and Methods available to manipulate that object. In the example below we are going to save a workbook.

Sub WorkbookObject()
'declare the workbook object
   Dim wkb as Workbook
'assign an unsaved workbook to the object
   Set wkb = Workbooks("Book1")
'save the workbook
   wkb.SaveAs "C:datatestbook.xlsx"
'close the workbook
   wkb.close
'remember to release the object
   Set wkb = Nothing
End Sub

Worksheet Object

Similarly you can manipulate a worksheet or worksheets once you have declared the worksheet as a variable. In the example below, we rename Sheet1 and Sheet2.

Sub WorksheetObject()
   Dim wks1 As Worksheet
   Dim wks2 As Worksheet
'initialize the objects
   Set wks1 = Sheet1
   Set wks2 = Sheet2
'rename the sheets
   wks1.Name = "Customers"
   wks2.Name = "Products"
'set the objects to nothing
   wks1 = Nothing
   wks2 = Nothing
End Sub

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

Range Object

The Range object is one of the most  useful objects to manipulate in Excel. In the example below, we bold Range A1 to E1 and format it with a bottom border.

Sub RangeObject()
Dim rng1 As Range
'intialize the range
   Set rng = Range("A1:E1")
'bold the range and set the bottom border
   rng.Font.Bold = True
   With rng1.Borders(xlEdgeBottom)
      .LineStyle = xlContinuous
      .ColorIndex = 0
      .TintAndShade = 0
      .Weight = xlThin
   End With
End Sub

Shape Object

You can also use object variables to work with shapes.

Sub AddShape()
   Dim shp As Shape
'create the shape
   Set shp = ActiveDocument.Shapes.AddShape(msoShapeSmileyFace, 68.25, 225.75, 136.5, 96#)
   With shp
'change inside colour and style
      .Fill.ForeColor.RGB = RGB(255, 255, 0)
      .Fill.Solid
'adjust the smile!
      .Adjustments.Item(1) = 0.07181
   End With
End Sub

Set — это присвоение переменной объекта.
Т.е. вот есть объект Лист1, теперь мы будем его называть Sh.
И в данном случае Лист1 это не имя и не название, а кодовое имя. И кстати с таким именем (именно вот таким) могут быть проблемы, я так не обращаюсь.

Ещё добавлю — в примере выше в общем нет смысла в этом
set sh = Лист1
т.к. нет проблем применять всюду непосредственно Лист1 — вся разница что на 3 символа больше.
Но бывает что без объектной переменной не обойтись, например

Visual Basic
1
2
3
4
Set oXhr = CreateObject("Microsoft.XMLHTTP")
Set oXml = oXhr.responseXML
Set oLatLng = oXml.getElementsByTagName("pos")(0)
getYandexMapsGeocode = oLatLng.Text

хотя можно бы так:

Visual Basic
1
getYandexMapsGeocode = CreateObject("Microsoft.XMLHTTP").responseXML.getElementsByTagName("pos")(0).Text

но согласитесь непонятнее, да и работать не будет, т.к. там ещё в середине было

Visual Basic
1
2
oXhr.Open "GET", sQuery, False
oXhr.send

или

Visual Basic
1
2
3
4
5
Function ReadTXTfile(ByVal filename As String) As String
    Set fso = CreateObject("scripting.filesystemobject")
    Set ts = fso.OpenTextFile(filename, 1, True): ReadTXTfile = ts.ReadAll: ts.Close
    Set ts = Nothing: Set fso = Nothing
End Function

или

Visual Basic
1
Set dic = CreateObject("scripting.dictionary")

Если словарь всего один — часто пишут без переменной, используя with, а вот если сразу два — то нужна переменная.

или

Visual Basic
1
2
3
4
5
6
    Set wb = Workbooks.Open(filename, False, True)
    For Each sh In wb.Worksheets
    ...
    Next sh
    wb.Close True
    Set wb = Nothing

или

Visual Basic
1
2
3
Sub SortSheets(ByRef wb As Workbook)
    With wb
        For i = 1 To .Worksheets.Count - 1

Понравилась статья? Поделить с друзьями:
  • Set vba excel описание
  • Set vba excel rows
  • Set up one word or two
  • Set up heading in word
  • Set this workbook excel vba