Какое действие реализует следующая инструкция dim mysheet as object

Раннее и позднее связывание переменных с экземплярами внешних и внутренних объектов в VBA Excel. Преимущества ранней привязки объектов. Примеры кода.

Связывание – это процесс назначения внутреннего или внешнего объекта переменной.

Внутренними называются объекты, которые принадлежат объектной модели Excel (Range, Sheet, Workbook, Chart). Внешние объекты не принадлежат объектной модели Excel. А также новый экземпляр Excel.Application является внешним объектом по отношению к тому экземпляру приложения Excel, из которого он создается.

Раннее связывание

Раннее связывание – это объявление переменной с определенным типом объекта или присвоение переменной, при ее объявлении, нового экземпляра внешнего объекта.

Определение типа объекта при ранней привязке выполняется еще до запуска приложения.

Объявление переменной определенного типа

Объявление переменной с определенным типом объекта:

‘Внутренние объекты

Dim myRange As Range

Dim mySheet As Sheets

Dim myWorkbook As Workbook

‘Внешние объекты

Dim myDictionary As Dictionary

Dim myExcel As Excel.Application

Dim myWord As Word.Application

При объявлении переменной с определенным типом объекта ранняя привязка уже осуществилась, но чтобы начать работу с переменной, ей необходимо присвоить конкретный (для внутренних объектов) или новый (для внешних объектов) экземпляр объекта с помощью ключевого слова Set:

‘Внутренние объекты

Set myRange = Range(«A1:D10»)

Set mySheet = Sheets(1)

Set myWorkbook = Workbooks.Open(«C:\Книга1.xlsm»)

‘Внешние объекты

Set myDictionary = New Dictionary

Set myExcel = New Excel.Application

Set myWord = New Word.Application

Присвоение переменной объекта при объявлении

Присвоение переменной, при ее объявлении, нового экземпляра внешнего объекта:

Dim myDictionary As New Dictionary

Dim myExcel As New Excel.Application

Dim myWord As New Word.Application

Ссылка на библиотеку внешнего объекта

Чтобы использовать раннее связывание для внешнего объекта, необходимо подключить в редакторе VBA Excel ссылку на библиотеку этого объекта, если она еще не подключена. Подключается ссылка на библиотеку в окне «References VBAproject», перейти в которое можно через главное меню редактора: Tools–>References…

Ссылка на библиотеку Microsoft Scripting Runtime, которая необходима для ранней привязки объекта Dictionary:

Ссылка на библиотеку Microsoft Word Object Library, которая необходима для ранней привязки объекта Word.Application:

После выбора библиотеки следует нажать кнопку «OK».

Преимущества ранней привязки

Главное преимущество раннего связывания заключается в возможности использовать при написании кода VBA Excel лист выбора и вставки свойств-методов привязанных объектов (Auto List Members). Лист подсказок отображается автоматически или вызывается сочетанием клавиш «Ctrl+Пробел» или «Ctrl+J».

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

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

Скопируйте процедуру Primer1 с ранней привязкой объекта Sheet в любой программный модуль:

Sub Primer1()

Dim mySheet As Sheet

mySheet

End Sub

Поставьте точку после mySheet в 3 строке и вы увидите лист выбора и вставки свойств-методов:

Если вдруг лист подсказок не отобразился автоматически, его можно вызвать сочетанием клавиш «Ctrl+Пробел» или «Ctrl+J».

Теперь скопируйте процедуру Primer2 с поздней привязкой объекта Sheet в любой программный модуль:

Sub Primer2()

Dim mySheet As Object

Set mySheet = Sheets(1)

mySheet

End Sub

Поставьте точку после mySheet в 4 строке – лист подсказок не отобразится:

Сочетания клавиш «Ctrl+Пробел» и «Ctrl+J» тоже не помогут. В данном случае тип объекта, присвоенного переменной, определяется только в процессе выполнения программы.

Позднее связывание

Позднее связывание – это присвоение переменной, объявленной как Object, экземпляра внутреннего объекта с помощью ключевого слова Set или экземпляра внешнего объекта с помощью ключевого слова Set и функции GetObject или CreateObject.

Тип объекта при поздней привязке определяется только в процессе выполнения программы.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

‘Внутренние объекты

‘Диапазон ячеек

Dim myRange As Object

Set myRange = Range(«A1:D10»)

‘Рабочий лист

Dim mySheet As Object

Set mySheet = Sheets(1)

‘Рабочая книга Excel

Dim myWorkbook As Object

Set myWorkbook = Workbooks.Open(«C:\Книга1.xlsm»)

‘Внешние объекты

‘Словарь

Dim myDictionary As Object

Set myDictionary = CreateObject(«Scripting.Dictionary»)

‘Приложение Excel

Dim myExcel As Object

Set myExcel = CreateObject(«Excel.Application»)

‘Приложение Word

Dim myWord As Object

Set myWord = CreateObject(«Word.Application»)

Функция CreateObject используется для создания нового экземпляра объекта, а функция GetObject – для получения сохраненного объекта.

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

Вы объявляете
объектную переменную, указывая либо
универсальный тип Object, либо конкретное
имя класса. Следующий оператор объявляет
объектную переменную типа Object:

Dim mySheet As Object

Если тип переменной
задан как Object, Visual Basic не знает, с объектами
какого типа Вы будете использовать ее
в дальнейшем. Поэтому Visual Basic при
компиляции не сможет проверить, существует
ли такой объект, корректно ли применяются
его методы и свойства, и не сумеет связать
эту информацию с объектной переменной
— иначе говоря, Visual Basic не выполнит
раннее связывание (early binding) объектной
переменной. Лишь когда Вы запустите
программу,
и этой переменной будет присвоена ссылка
на конкретный объект, Visual Basic получит
нужную информацию и выполнит позднее
связывание (late binding). Универсальные
объектные переменные полезны только в
том случае, когда Вам заранее не известен
конкретный тип объекта или когда за
переменной периодически закрепляются
объекты разных классов. Так что по
возможности указывайте при объявлении
объектной переменной имя конкретного
класса, например,
так:

Dim mySheet As Worksheet

Dim myPres As Presentation

Dim myRange As Range

Dim
myApp As Application

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

Dim wndXL As
Excel.Window

Dim wndWD As Word.Window

Dim appWD As
Word.Application

Для закрепления
объекта за переменной предназначен
оператор Set:

Dim myRange As Excel.
Range

Set myRange = Worksheets(«Sheet1»).Range(«A1»)

Если Вы не объявили
объектную переменную явно и в момент
присвоения забыли указать ключевое
слово Set, Visual Basic не закрепит объект за
этой переменной, а присвоит ей значение
свойства объекта по умолчанию. В следующем
примере переменная myRange получает значение
свойства по умолчанию объекта Range
(каковым является свойство Value):

myRange =
Worksheets(«Sheet1»).Range(«A1»)

‘ пропущен
оператор Set!

1.2.4. Встроенные константы

Библиотека объектов
каждого приложения Office 97 предоставляет
набор встроенных констант, которые
можно использовать для задания значений
свойств или передачи аргументов свойствам
и методам. Набор встроенных констант,
отражающих допустимые значения
какого-либо свойства или параметра,
передаваемого методу или свойству,
представляется перечислимым типом. Для
многих свойств и методов в качестве
типа возвращаемого значения или параметра
Вы увидите в Object Browser (средство просмотра
объектов) именно перечислимый, а не
базовый тип данных. Чтобы открыть в
Visual Basic Editor окно Object Browser (Просмотр
объектов), нажмите клавишу F2. С его
помощью можно просмотреть, какие
константы составляют перечислимый тип,
и каковы их значения. Например, в списке
Classes (Классы) щелкните строку Application, а
в списке Members Of (Компонент) — строку
Display Alerts. В нижней части окна Object Browser
(Просмотр объектов) Вы увидите следующий
текст:

Property DisplayAlerts
As WdAlertLevel

WdAlertLevel — перечислимый
тип, объединяющий константы, которые
представляют все допустимые значения
свойства DisplayAlerts. Перечислимый тип
нетрудно узнать по имени, поскольку оно
всегда начинается с префикса, обозначающего
библиотеку объектов, в которой определен
этот тип, — например: Mso, Wd, Xl, Ac, Pp, VB или
Fm. (Имена встроенных констант начинаются
с тех же префиксов, что и имена перечислимых
типов.) Чтобы просмотреть константы
перечислимого типа, щелкните подчеркнутую
строку WdAlertLevel. После этого WdAlertLevel станет
текущим в списке классов Object Browser,
и константы этого типа появятся в списке
Members Of (Компонент). Если щелкнуть одну
из констант, в нижней части окна Object
Browser (Просмотр объектов) будет показано
значение, которое представляет данная
константа. Подробнее об использовании
диалогового окна Object Browser см. главу 2
“Введение в модели объектов”.

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

Application.DisplayAlerts =
-1

Application.DisplayAlerts =
wdAlertsAII

Константы легче
читать, чем литеральные значения. Кроме
того, если эти значения в будущих версиях
приложений изменятся, Вам вряд ли
придется модифицировать программу,
использующую константы. Вполне вероятно,
что литеральное значение -1 больше не
будет соответствовать параметру,
заставляющему выводить все предупреждения
и сообщения, но константа wdAlertsAll — будет
обязательно.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #

“One man’s constant is another man’s variable.” – Alan Perlis

This post provides a complete guide to using the VBA Dim statement.

The first section provides a quick guide to using the Dim statement including examples and the format of the Dim statement.

The rest of the post provides the most complete guide you will find on the VBA Dim Statement.

If you are interested in declaring parameters then you can read about them here.

Contents

  • 1 A Quick Guide to using the VBA Dim Statement
  • 2 Useful Links
  • 3
  • 4 What is the VBA Dim Statement
  • 5
  • 6 Format of the VBA Dim Statement
  • 7 How to Use Dim with Multiple Variables
  • 8
  • 9 Where Should I Put the Dim Statement?
  • 10
  • 11 Using Dim in Loops
  • 12 Can I use Dim to Assign a Value?
  • 13
  • 14 Is Dim Actually Required?
    • 14.1 Option Explicit
    • 14.2 Variable Errors
    • 14.3
    • 14.4 Keyword Misspelt Error
  • 15
  • 16 Using Dim with Basic Variables
    • 16.1 Fixed String Type
  • 17 Using Dim with Variants
    • 17.1
    • 17.2 Runtime Errors
    • 17.3 Compile Errors
    • 17.4
    • 17.5 Accessing the Intellisense
    • 17.6 Variant Size
  • 18 Using Dim with Objects
    • 18.1
    • 18.2 Excel objects
    • 18.3 Using Dim with Class Module Objects
    • 18.4 Objects from an External Library
      • 18.4.1
      • 18.4.2 Early Binding
      • 18.4.3
      • 18.4.4 Late Binding
  • 19 Using Dim with Arrays
    • 19.1 Using ReDim
  • 20 Troubleshooting Dim Errors
  • 21 Local versus Module versus Global Variables
    • 21.1 Dim versus Private versus Public
  • 22 Conclusion
  • 23 What’s Next?

A Quick Guide to using the VBA Dim Statement

Description Format Example
Basic variable Dim [variable name] As [Type] Dim count As Long
Dim amount As Currency
Dim name As String
Dim visible As Boolean
Fixed String Dim [variable name] As String * [size] Dim s As String * 4
Dim t As String * 10
Variant Dim [variable name] As Variant
Dim [variable name]
Dim var As Variant
Dim var
Object using Dim and New Dim [variable name] As New [object type] Dim coll As New Collection
Dim coll As New Class1
Object using Dim, Set and New Dim [variable name] As [object type]
Set [variable name] = New [object type]
Dim coll As Collection
Set coll = New Collection

Dim coll As Class1
Set coll = New Class1

Static array Dim [variable name]([first] To [last] ) As [Type] Dim arr(1 To 6) As Long
Dynamic array Dim [variable name]() As [Type]
ReDim [variable name]([first] To [last])
Dim arr() As Long
ReDim arr(1 To 6)
External Library
(Early Binding)*
Dim [variable name] As New [item] Dim dict As New Dictionary
External Library
(Early Binding using Set)*
Dim [variable name] As [item]
Set [variable name] = New [item]
Dim dict As Dictionary
Set dict = New Dictonary
External Library
(Late Binding)
Dim [variable name] As Object
Set [variable name] = CreateObject(«[library]»)
Dim dict As Object
Set dict = CreateObject(«Scripting.Dictionary»)

*Note: Early binding requires that you add the reference file using Tools->References from the menu. See here for how to add the Dictonary reference.

Useful Links

Declaring parameters in a sub or function
Using Objects in VBA
VBA Arrays
VBA Collection
VBA Dictionary
VBA Workbook
VBA Worksheet

What is the VBA Dim Statement

The Dim keyword is short for Dimension. It is used to declare variables in VBA.

Declare means we are telling VBA about a variable we will use later.

There are four types of Dim statements. They are all pretty similar in terms of syntax.

They are:

  1. Basic variable
  2. Variant
  3. Object
  4. Array

The following is a brief description of each type:

    1. Basic variable – this variable type holds one value. These are the types such as Long, String, Date, Double, Currency.
    1. Variant – VBA decides at runtime which type will be used. You should avoid variants where possible but in certain cases it is a requirement to use them.
    1. Object – This is a variable that can have multiple methods(i.e. subs/functions) and multiple properties(i.e. values). There are 3 kinds:
      1. Excel objects such as the Workbook, Worksheet and Range objects.
      2. User objects created using Class Modules.
      3. External libraries such as the Dictionary.
  1. Array – this is a group of variables or objects.

In the next section, we will look at the format of the VBA Dim statement with some examples of each.

In later sections we will look at each type in more detail.

Format of the VBA Dim Statement

The format of the Dim statement is shown below

' 1. BASIC VARIABLE
' Declaring a basic variable
Dim [variable name] As [type]

' Declaring a fixed string
Dim [variable name] As String * [size]

' 2. VARIANT
Dim [variable name] As Variant
Dim [variable name]

' 3. OBJECT
' Declaring an object
Dim [variable name] As [type]

' Declaring and creating an object
Dim [variable name] As New [type]

' Declaring an object using late binding
Dim [variable name] As Object

' 4. ARRAY
' Declaring a static array
Dim [variable name](first To last) As [type]

' Declaring a dynamic array
Dim [variable name]() As [type]

Below are examples of using the different formats

' https://excelmacromastery.com/
Sub Examples()

    ' 1. BASIC VARIABLE
    ' Declaring a basic variable
    Dim name As String
    Dim count As Long
    Dim amount As Currency
    Dim eventdate As Date
    
    ' Declaring a fixed string
    Dim userid As String * 8
    
    ' 2. VARIANT
    Dim var As Variant
    Dim var
    
    ' 3. OBJECT
    ' Declaring an object
    Dim sh As Worksheet
    Dim wk As Workbook
    Dim rg As Range
    
    ' Declaring and creating an object
    Dim coll1 As New Collection
    Dim o1 As New Class1
    
    ' Declaring an object - create object below using Set
    Dim coll2 As Collection
    Dim o2 As Class1
    
    Set coll2 = New Collection
    Set o2 = New Class1
    
    ' Declaring and assigning using late binding
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' 4. ARRAY
    ' Declaring a static array
    Dim arrScores(1 To 5) As Long
    Dim arrCountries(0 To 9) As String
    
    ' Declaring a dynamic array - set size below using ReDim
    Dim arrMarks() As Long
    Dim arrNames() As String
    
    ReDim arrMarks(1 To 10) As Long
    ReDim arrNames(1 To 10) As String

End Sub

We will examine these different types of Dim statements in the later sections.

How to Use Dim with Multiple Variables

We can declare multiple variables in a single Dim statement

Dim name As String, age As Long, count As Long

If we leave out the type then VBA automatically sets the type to be a Variant. We will see more about Variant later.

' Amount is a variant
Dim amount As Variant

' Amount is a variant
Dim amount

' Address is a variant - name is a string
Dim name As String, address

' name is a variant, address is a string
Dim name, address As String

When you declare multiple variables you should specify the type of each one individually

Dim wk As Workbook, marks As Long, name As String

You can place as many variables as you like in one Dim statement but it is good to keep it to 3 or 4 for readability.

Where Should I Put the Dim Statement?

The Dim statement can be placed anywhere in a procedure. However, it must come before any line where the variable is used.

If the variable is used before the Dim statement then you will get a “variable not defined” error:

When it comes to the positioning your Dim statements you can do it in two main ways. You can place all your Dim statements at the top of the procedure:

' https://excelmacromastery.com/
Sub DimTop()

    ' Placing all the Dim statements at the top
    Dim count As Long, name As String, i As Long
    Dim wk As Workbook, sh As Worksheet, rg As Range
    
    Set wk = Workbooks.Open("C:\Docs\data.xlsx")
    Set sh = wk.Worksheets(1)
    Set rg = sh.Range("A1:A10")
    
    For i = 1 To rg.Rows.count
        count = rg.Value
        Debug.Print count
    Next i
  
End Sub

OR you can declare the variables immediately before you use them:

' https://excelmacromastery.com/
Sub DimAsUsed()

    Dim wk As Workbook
    Set wk = Workbooks.Open("C:\Docs\data.xlsx")
    
    Dim sh As Worksheet
    Set sh = wk.Worksheets(1)
    
    Dim rg As Range
    Set rg = sh.Range("A1:A10")
    
    Dim i As Long, count As Long, name As String
    For i = 1 To rg.Rows.count
        count = rg.Value
        name = rg.Offset(0, 1).Value
        Debug.Print name, count
    Next i
  
End Sub

I personally prefer the latter as it makes the code neater and it is easier to read, update and spot errors.

Using Dim in Loops

Placing a Dim statement in a Loop has no effect on the variable.

When VBA starts a Sub (or Function), the first thing it does is to create all the variables that have been declared in the Dim statements.

The following 2 pieces of code are almost the same. In the first, the variable Count is declared before the loop. In the second it is declared within the loop.

' https://excelmacromastery.com/
Sub CountOutsideLoop()

    Dim count As Long

    Dim i As Long
    For i = 1 To 3
        count = count + 1
    Next i
    
    ' count value will be 3
    Debug.Print count

End Sub
' https://excelmacromastery.com/
Sub CountInsideLoop()

    Dim i As Long
    For i = 1 To 3
        Dim count As Long
        count = count + 1
    Next i
    
    ' count value will be 3
    Debug.Print count

End Sub

The code will behave exactly the same because VBA will create the variables when it enters the sub.

Can I use Dim to Assign a Value?

In languages like C++, C# and Java, we can declare and assign variables on the same line

' C++
int i = 6
String name = "John"

We cannot do this in VBA. We can use the colon operator to place the declare and assign lines on the same line.

Dim count As Long: count = 6

We are not declaring and assigning in the same VBA line. What we are doing is placing these two lines(below) on one line in the editor. As far as VBA is concerned they are two separate lines as here:

Dim count As Long
count = 6

Here we put 3 lines of code on one editor line using the colon:

count = 1: count = 2: Set wk = ThisWorkbook

There is really no advantage or disadvantage to assigning and declaring on one editor line. It comes down to a personal preference.

Is Dim Actually Required?

The answer is that it is not required. VBA does not require you to use the Dim Statement.

However, not using the Dim statement is a poor practice and can lead to lots of problems.

You can use a variable without first using the Dim statement. In this case the variable will automatically be a variant type.

This can lead to problems such as

  1. All variables are variants (see the Variant section for issues with this).
  2. Some variable errors will go undetected.

Because of these problems it is good practice to make using Dim mandatory in our code. We do this by using the Option Explicit statement.

Option Explicit

We can make Dim mandatory in a module by typing “Option Explicit” at the top of a module.

We can make this happen automatically in each new module by selecting Tools->Options from the menu and checking the box beside “Require Variable Declaration”. Then when you insert a new module, “Option Explicit” will be automatically added to the top.

VBA Require Variable Declaration

Let’s look at some of the errors that may go undetected if we don’t use Dim.

Variable Errors

In the code below we use the Total variable without using a Dim statement

' https://excelmacromastery.com/
Sub NoDim()

    Total = 6
    
    Total = Total + 1
    
    Debug.Print Total

End Sub

If we accidentally spell Total incorrectly then VBA will consider it a new variable.

In the code below we have misspelt the variable Total as Totall:

' https://excelmacromastery.com/
Sub NoDimError()

    Total = 6
    
    ' The first Total is misspelt
    Totall = Total + 1
    
    ' This will print 6 instead of 7
    Debug.Print Total

End Sub

VBA will not detect any error in the code and an incorrect value will be printed.

Let’s add Option Explicit and try the above code again

' https://excelmacromastery.com/
Option Explicit 

Sub NoDimError()

    Total = 6
    
    ' The first Total is misspelt
    Totall = Total + 1
    
    ' This will print 6 instead of 7
    Debug.Print Total

End Sub

Now when we run the code we will get the “Variable not defined” error. To stop this error appearing we must use Dim for each variable we want to use.

When we add the Dim statement for Total and run the code we will now get an error telling us that the misspelt Totall was not defined.

variable not defined 2

This is really useful as it helps us find an error that would have otherwise gone undetected.

Keyword Misspelt Error

Here is a second example which is more subtle.

When the following code runs it should change the font in cell A1 to blue.

However, when the code runs nothing happens.

' https://excelmacromastery.com/
Sub SetColor()

    Sheet1.Range("A1").Font.Color = rgblue

End Sub

The error here is that rgblue should be rgbBlue. If you add Option Explicit to the module, the error “variable not defined” will appear. This makes solving the problem much easier.

These two examples are very simple. If you have a lot of code then errors like this can be a nightmare to track down.

Using Dim with Basic Variables

VBA has the same basic variable types that are used in the Excel Spreadsheet.

You can see a list of all the VBA variable types here.

However, most of the time you will use the following ones

Type Storage Range Description
Boolean 2 bytes True or False This variable can be either True or False.
Long 4 bytes -2,147,483,648 to 2,147,483,647 Long is short for Long Integer. Use this instead of the Integer* type.
Currency 8 bytes -1.79769313486231E308 to-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values Similar to Double but has only 4 decimal places
Double 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Date 8 bytes January 1, 100 to December 31, 9999
String varies 0 to approximately 2 billion Holds text.

*Originally we would use the Long type instead of Integer because the Integer was 16-bit and so the range was -32,768 to 32,767 which is quite small for a lot of the uses of integer.

However on a 32 bit(or higher) system the Integer is automatically converted to a Long. As Windows has been 32 bit since Windows 95\NT there is no point in using an Integer.

In a nutshell, always use Long for an integer type in VBA.

Fixed String Type

There is one unusual basic variable type in VBA that you may not be familiar with.

This is the fixed string type. When we create a normal string in VBA we can add text and VBA will automatically resize the string for us

' https://excelmacromastery.com/
Sub StringType()

    Dim s As String
    
    ' s is "John Smith"
    s = "John Smith"
    
    ' s is "Tom"
    s = "Tom"

End Sub

A fixed string is never resized. This string will always be the same size no matter what you assign to it

Here are some examples

' https://excelmacromastery.com/
Sub FixedString()
    
    Dim s As String * 4
    
    ' s is "John"
    s = "John Smith"
    
    ' s = "Tom "
    s = "Tom"

End Sub

Using Dim with Variants

When we declare a variable to be a variant, VBA will decide at runtime which variable type it should be.

We declare variants as follows

' Both are variants
Dim count
Dim count As Variant

This sounds like a great idea in theory. No more worrying about the variable type

' https://excelmacromastery.com/
Sub UsingVariants()
    
    Dim count As Variant
        
    count = 7
    
    count = "John"
    
    count = #12/1/2018#

End Sub

However, using variants is poor practice and this is why:

  1. Runtime Errors – VBA will not notice incorrect type errors(i.e. Data Mismatch).
  2. Compile Errors – VBA cannot detect compile errors.
  3. Intellisense is not available.
  4. Size – A variant is set to 16 bytes which is the largest variable type

Runtime Errors

Errors are your friend!

They may be annoying and frustrating when they happen but they are alerting you to future problems which may not be so easy to find.

The Type Mismatch error alerts you when incorrect data is used.

For example. Imagine we have a sheet of student marks. If someone accidentally(or deliberately) replaces a mark with text then the data is invalid.

If we use a variant to store marks then no error will occur:

' https://excelmacromastery.com/
Sub MarksVariant()
    
    Dim mark As Variant
    
    Dim i As Long
    For i = 1 To 10
        
        ' Read the mark
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

This is not good because there is an error with your data and you are not aware of it.

If you make the variable Long then VBA will alert you with a “Type Mismatch” error if the values are text.

' https://excelmacromastery.com/
Sub MarksLong()
    
    Dim mark As Long
    
    Dim i As Long
    For i = 1 To 10
        
        ' Read the mark
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

Compile Errors

Using the compiler to check for errors is very efficient. It will check all of your code for problems before you run it. You use the compiler by selecting Debug->Compile VBAProject from the menu.

In the following code, there is an error. The Square function expects a long integer but we are passing a string(i.e. the name variable):

' https://excelmacromastery.com/
Sub CompileError()

    Dim name As String

    Debug.Print Square(name)

End Sub

Function Square(value As Long) As Long
    Square = value * value
End Function

If we use Debug->Compile on this code, VBA will show us an error:

dim compile error

This is good news as we can fix this error right away. However, if we declare the value parameter as a variant:

Function Square(value As Variant) As Long
    Square = value * value
End Function

then Debug.Compile will not treat this as an error. The error is still there but it is undetected.

Accessing the Intellisense

The Intellisense is an amazing feature of VBA. It gives you the available options based on the type you have created.

Imagine you declare a worksheet variable using Dim

Dim wk As Workbook

When you use the variable wk with a decimal point, VBA will automatically display the available options for the variable.

You can see the Intellisense in the screenshot below

VBA Intellisense

If you use Variant as a type then the Intellisense will not be available

Dim wk As Variant

This is because VBA will not know the variable type until runtime.

Variant Size

The size of a variant is 16 bytes. If the variable is going to be a long then it would only take up 4 bytes. You can see that this is not very efficient.

However, unlike the 1990’s where this would be an issue, we now have computers with lots of memory and it is unlikely you will notice an inefficiency unless you are using a huge amount of variables.

Using Dim with Objects

If you don’t know what Objects are then you can read my article about VBA Objects here.

There are 3 types of objects:

  1. Excel objects
  2. Class Module objects
  3. External library objects

Note: The VBA Collection object is used in a similar way to how we use Class Module object. We use new to create it.

Let’s look at each of these in turn.

Excel objects

Excel objects such as the Workbook, Worksheet, Range, etc. do not use New because they are automatically created by Excel. See When New is not required.

When a workbook is created or opened then Excel automatically creates the associated object.

For example, in the code below we open a workbook. VBA will create the object and the Open function will return a workbook which we can store in a variable

' https://excelmacromastery.com/
Sub OpenWorkbook()
    
    Dim wk As Workbook
    Set wk = Workbooks.Open("C:\Docs\data.xlsx")

End Sub

If we create a new worksheet, a similar thing happens. VBA will automatically create it and provide use access to the object.

' https://excelmacromastery.com/
Sub AddSheet()
    
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets.Add

End Sub

We don’t need to use the New keyword for these Excel objects.

We just assign the variable to the function that either creates a new object or that gives us access to an existing one.

Here are some examples of assigning the Workbook, Worksheet and range variables:

' https://excelmacromastery.com/
Sub DimWorkbook()
    
    Dim wk As Workbook
    
    ' assign wk to a new workbook
    Set wk = Workbooks.Add
    
    ' assign wk to the first workbook opened
    Set wk = Workbooks(1)
    
    ' assign wk to The workbook Data.xlsx
    Set wk = Workbooks("Data.xlsx")
    
    ' assign wk to the active workbook
    Set wk = ActiveWorkbook
    
End Sub
' https://excelmacromastery.com/
Sub DimWorksheet()
    
    Dim sh As Worksheet
    
    ' Assign sh to a new worksheet
    Set sh = ThisWorkbook.Worksheets.Add
    
    ' Assign sh to the leftmost worksheet
    Set sh = ThisWorkbook.Worksheets(1)
    
    ' Assign sh to a worksheet called Customers
    Set sh = ThisWorkbook.Worksheets("Customers")
    
    ' Assign sh to the active worksheet
    Set sh = ActiveSheet

End Sub
' https://excelmacromastery.com/
Sub DimRange()

    ' Get the customer worksheet
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Customers")
    
    ' Declare the range variable
    Dim rg As Range
    
    ' Assign rg to range A1
    Set rg = sh.Range("A1")
    
    ' Assign rg to range B4 to F10
    Set rg = sh.Range("B4:F10")
    
    ' Assign rg to range E1
    Set rg = sh.Cells(1, 5)
    
End Sub

If you want to know more about these objects you can check out these articles: VBA Workbook, VBA Worksheet and VBA Ranges and Cells.

Using Dim with Class Module Objects

In VBA we use Class Modules to create our own custom objects. You can read all about Class Modules here.

If we are creating an object then we need to use the New keyword.

We can do this in the Dim statement or in the Set statement.

The following code creates an object using the New keyword in the Dim statement:

' Declare and create
Dim o As New class1
Dim coll As New Collection

Using New in a Dim statement means that exactly one object will be created each time our code runs.

Using Set gives us more flexibility. We can create many objects from one variable. We can also create an object based on a condition.

This following code shows how we create a Class Module object using Set.

(To create a Class Module, go to the project window, right-click on the appropiate workbook and select “Insert Class Module”. See Creating a Simple Class Module for more details.)

' Declare only
Dim o As Class1

' Create using Set
Set o = New Class1

Let’s look at an example of using Set. In the code below we want to read through a range of data. We only create an object if the value is greater than 50.

We use Set to create the Class1 object. This is because the number of objects we need depends on the number of values over 50.

' https://excelmacromastery.com/
Sub UsingSet()
    
    ' Declare a Class1 object variable
    Dim o As Class1
    
    ' Read a range
    Dim i As Long
    For i = 1 To 10
        If Sheet1.Range("A" & i).Value > 50 Then

            ' Create object if condition met
            Set o = New Class1
            
        End If
    Next i

End Sub

I’ve kept this example simple for clarity. In a real-world version of this code we would fill the Class Module object with data and add it to a data structure like a Collection or Dictionary.

Here is an example of a real-world version based on the data below:

dim sample data

' Class Module - clsStudent
Public Name As String
Public Subject As String

' Standard Module
' https://excelmacromastery.com/
Sub ReadMarks()

    ' Create a collection to store the objects
    Dim coll As New Collection
    
    ' Current Region gets the adjacent data
    Dim rg As Range
    Set rg = Sheet1.Range("A1").CurrentRegion
    
    Dim i As Long, oStudent As clsStudent
    For i = 2 To rg.Rows.Count
        
        ' Check value
        If rg.Cells(i, 1).Value > 50 Then
            ' Create the new object
            Set oStudent = New clsStudent
            
            ' Read data to the student object
            oStudent.Name = rg.Cells(i, 2).Value
            oStudent.Subject = rg.Cells(i, 3).Value
            
            ' add the object to the collection
            coll.Add oStudent
            
        End If
        
    Next i
    
    ' Print the data to the Immediate Window to test it
    Dim oData As clsStudent
    For Each oData In coll
        Debug.Print oData.Name & " studies " & oData.Subject
    Next oData

End Sub

To learn more about Set you can check out here.

Objects from an External Library

A really useful thing we can do with VBA is to access external libraries. This opens up a whole new world to what we can do.

Examples are the Access, Outlook and Word libraries that allow us to communicate with these applications.

We can use libraries for different types of data structures such as the Dictionary, the Arraylist, Stack and Queue.

There are libraries for scraping a website (Microsoft HTML Object Library), using Regular Expressions (Microsoft VBScript Regular Expressions) and many other tasks.

We can create these objects in two ways:

  1. Early Binding
  2. Late Binding

Let’s look at these in turn.

Early Binding

Early binding means that we add a reference file. Once this file is added we can treat the object like a class module object.

We add a reference using Tools->Reference and then we check the appropriate file in the list.

For example, to use the Dictionary we place a check on “Microsoft Scripting Runtime”:

vba references dialog

Once we have the reference added we can use the Dictionary like a class module object

' https://excelmacromastery.com/
Sub EarlyBinding()

    ' Use Dim only
    Dim dict1 As New Dictionary
    
    ' Use Dim and Set
    Dim dict2 As Dictionary
    Set dict2 = New Dictionary

End Sub

The advantage of early binding is that we have access to the Intellisense. The disadvantage is that it may cause conflict issues on other computers.

The best thing to do is to use early binding when writing the code and then use late binding if distributing your code to other users.

Late Binding

Late binding means that we create the object at runtime.

We declare the variable as an “Object” type. Then we use CreateObject to create the object.

' https://excelmacromastery.com/
Sub LateBinding()

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
End Sub

Using Dim with Arrays

There are two types of arrays in VBA. They are:

  1. Static – the array size is set in the Dim statement and it cannot change.
  2. Dynamic – the array size is not set in the Dim statement. It is set later using the ReDim statement.
' STATIC ARRAY

' Stores 7 Longs - 0 to 6
Dim arrLong(0 To 6) As Long

' Stores 7 Strings - 0 to 6
Dim arrLong(6) As String

A dynamic array gives us much more flexibility. We can set the size while the code is running.

We declare a dynamic array using the Dim statement and we set the size later using ReDim.

' DYNAMIC ARRAY

' Declare the variable
Dim arrLong() As Long

' Set the size
ReDim arrLong(0 To 6) As Long

Using ReDim

The big difference between Dim and ReDim is that we can use a variable in the ReDim statement. In the Dim statement, the size must be a constant value.

' https://excelmacromastery.com/
Sub UserSet()

    ' Declare the variable
    Dim arrLong() As Long
    
    ' Ask the user for the size
    Dim size As Long
    size = InputBox("Please enter the size of the array.", Default:=1)
    
    ' Set the size based on the user input
    ReDim arrLong(0 To size) As Long

End Sub

We can actually use the Redim Statement without having first used the Dim statement.

In the first example you can see that we use Dim:

' https://excelmacromastery.com/
Sub UsingDimReDim()

    ' Using Dim
    Dim arr() As String

    ReDim arr(1 To 5) As String
    
    arr(1) = "Apple"
    arr(5) = "Orange"
    
End Sub

In the second example we don’t use Dim:

' https://excelmacromastery.com/
Sub UsingReDimOnly()

    ' Using  ReDim only
    ReDim arr(1 To 5) As String
    
    arr(1) = "Apple"
    arr(5) = "Orange"
    
End Sub

The advantage is that you don’t need the Dim statement. The disadvantage is that it may confuse someone reading your code. Either way it doesn’t make much difference.

You can use the Preserve keyword with ReDim to keep existing data while you resize an array. You can read more about this here here.

You can find everything you need to know about arrays in VBA here.

Troubleshooting Dim Errors

The table below shows the errors that you may encounter when using Dim. See VBA Errors for an explanation of the different error types.

Error Type Cause
Array already dimensioned Compile Using Redim on an array that is static
Expected: identifier Syntax Using a reserved word as the variable name
Expected: New of type name Syntax The type is missing from the Dim statement
Object variable or With block variable not set Runtime New was not used to create the object(see Creating an Object)
Object variable or With block variable not set Runtime Set was not used to assign an object variable.
User-defined type not defined Compile The type is not recognised. Can happen if a reference file is not added under Tools->Reference or the Class Module name is spelled wrong.
Statement invalid outside Type block Compile Variable name is missing from the Dim statement
Variable not defined Compile The variable is used before the Dim line.

Local versus Module versus Global Variables

When we use Dim in a procedure (i.e. a Sub or Function), it is considered to be local. This means it is only available in the procedure where it is used.

The following are the different types of variables found in VBA:

  • Local variables are variables that are available to the procedure only. Local variables are declared using the Dim keyword.
  • Module variables are variables that are only available in the current module only. Module variables are declared using the Private keyword.
  • Global variables are variables that are available to the entire project. Global variables are declared using the Public keyword.

In the code below we have declared count as a global variable:

 ' Global
 ' https://excelmacromastery.com/
 Public count As Long

 Sub UseCount1()

    count = 6
    
 End Sub

 Sub UseCount2()

    count = 4
    
 End Sub

What happens if we have a global variable and a local variable with the same name?

It doesn’t actually cause an error. VBA gives the local declaration precedence:

 ' https://excelmacromastery.com/

 ' Global
 Public count As Long 

 Sub UseCount()
    ' Local
    Dim count As Long
    
    ' Refers to the local count
    count = 6
    
 End Sub

Having a situation like this can only lead to trouble as it is difficult to track which count is being used.

In general global variables should be avoided. They make the code very difficult to read because their values can be changed anywhere in the code. This makes errors difficult to spot and resolve.

The one use of a global variable is retaining a value between code runs. This can be useful for certain applications where you want to ‘remember’ a value after the code has stopped running.

In the code below we have a sub called Update. Each time we run the Update sub(using Run->Run Sub from the menu or F5) it will add 5 to the amount variable and print the result to the Immediate Window(Ctrl + G to view this window):

 Public amount As Long

 Sub Update()
    amount = amount + 5
    Debug.Print "Update: " & amount
 End Sub

The results are:

First run: amount = 5

Second run: amount = 10

Third run: amount = 15

and so on.

If we want to clear all global variable values then we can use the End keyword. Note that the End keyword will stop the code and reset all variables so you should only use it as the last line in your code.

Here is an example of using the End keyword:

Sub ResetAllGlobals()
    End ' Resets all variables and ends the current code run
End Sub

Dim versus Private versus Public

We can declare variables using Public, Private and Dim. In some cases, they can be used interchangeably.

However, the following is the convention we use for each of the declaration keywords:

  1. Dim – used to declare local variables i.e. available only in the current procedure.
  2. Private – used to declare module variables and procedures. These are available within the current module only.
  3. Public – used to declare global variables and procedures. These are available throughout the project.
  4. Global(obsolete) – an older and obsolete version of Public. Can only be used in standard modules. It only exists for backward compatibility.

Note the Public and Private keywords are also used within Class Modules.

Conclusion

This concludes the article on the VBA Dim Statement. If you have any questions or thoughts then please let me know in the comments below.

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

06-25-2005, 08:05 PM


#1

Dim mySheet As New Worksheet

Hi all,

I will be stupid, a moron, etc. but … How to continue after
Sub NoGo()
Dim mySheet As New Worksheet
?
End Sub

The line
Dim X As New Worksheet
is stated in the VBA-help but that’s all.

I can do with:
Sub WillGo()
Dim mySheet As Worksheet
Set mySheet = Worksheets.Add

End Sub

And also:
Sub Splendid()
Dim myApp As New Application

End Sub

Please give me any usefull, working code sample with
Dim mySheet As New Worksheet
Or explain why is doesn’t work and still it is in the help.

Thanks, Frans van Zelm


06-25-2005, 08:05 PM


#2

Re: Dim mySheet As New Worksheet

> Dim mySheet As New Worksheet
this mean mySheet is ready to be a sheet
> Set mySheet = Worksheets.Add

add is a method wich mean you want to add a sheet to the book
then, you re-use this object and decide to store the added new sheet to
mySheet.
> Please give me any usefull, working code sample with
> Dim mySheet As New Worksheet
> Or explain why is doesn’t work and still it is in the help.

what does not exactly work ?
it works perfectly:
it does what you wrote, maybe not what you wish :-)

the real question is: what to you want to do ?

an example:
mysheet.Range(«A1»).value = mysheet.name
this will add the name of the new created sheet in its A1 cell


06-25-2005, 09:05 PM


#3

Re: Dim mySheet As New Worksheet

Hi abcd,

Thanks for your reply but I still don’t get the point of New.
The help says that using New makes Set not neccessary.
Both samples below work but both need Set. So what is the point of New?

Sub Try1()
Dim mySheet As New Worksheet
Set mySheet = Worksheets.Add
mySheet.Range(«A1»).Value = mySheet.Name
End Sub

Sub Try2()
Dim mySheet As Worksheet
Set mySheet = Worksheets.Add
mySheet.Range(«A1»).Value = mySheet.Name
End Sub

Frans

«abcd» <temp.nospamdc2@gmail.com> wrote in message
news:%23$RSD7deFHA.2888@TK2MSFTNGP15.phx.gbl…


> > Dim mySheet As New Worksheet

> this mean mySheet is ready to be a sheet
>
>
> > Set mySheet = Worksheets.Add

> add is a method wich mean you want to add a sheet to the book
> then, you re-use this object and decide to store the added new sheet to
> mySheet.
>
>
> > Please give me any usefull, working code sample with
> > Dim mySheet As New Worksheet
> > Or explain why is doesn’t work and still it is in the help.

>
> what does not exactly work ?
> it works perfectly:
> it does what you wrote, maybe not what you wish :-)
>
>
> the real question is: what to you want to do ?
>
> an example:
> mysheet.Range(«A1»).value = mysheet.name
> this will add the name of the new created sheet in its A1 cell


06-25-2005, 09:05 PM


#4

Re: Dim mySheet As New Worksheet

There is more information available here…

Including: «Don’t Use The New Keyword In A Dim Statement»
http://www.cpearson.com/excel/variables.htm

Jim Cone
San Francisco, USA

«Frans van Zelm» <fhvzelm@hotmail.com> wrote in message
news:OFmH70deFHA.1680@TK2MSFTNGP09.phx.gbl…
Hi all,
I will be stupid, a moron, etc. but … How to continue after
Sub NoGo()
Dim mySheet As New Worksheet
?
End Sub
The line
Dim X As New Worksheet
is stated in the VBA-help but that’s all.
I can do with:
Sub WillGo()
Dim mySheet As Worksheet
Set mySheet = Worksheets.Add

End Sub
And also:
Sub Splendid()
Dim myApp As New Application

End Sub
Please give me any usefull, working code sample with
Dim mySheet As New Worksheet
Or explain why is doesn’t work and still it is in the help.
Thanks, Frans van Zelm


06-25-2005, 10:05 PM


#5

Re: Dim mySheet As New Worksheet

a worksheet is not a type of data but is an object: that’s all the
difference

you can type
dim A as string
but
dim S as worksheet
doesn’t mean anything because a sheet is not a type of data but is an
object. So «new object» is the syntax.

It’s just a syntax question: this makes you remember what your are
edaling with, but also makes differences inside the VBA motor:
creating a sheet is in memory creating many data (size, cells, colors,
etc.) so the «set» (and not = ) means «launch the procedure to
duplicate all the data of a sheet». It’s not one data, not an array of
data but a whole structure of data.

It’s usefull: the evidence is that it makes you think about the
difference beteween a sheet and a string : one is an object


06-25-2005, 11:05 PM


#6

Re: Dim mySheet As New Worksheet

Not sure what you mean but your statement:

dim S as worksheet
doesn’t mean anything

is incorrect.

Vasant

«abcd» <temp.nospamdc2@gmail.com> wrote in message
news:ehmv5KfeFHA.3932@TK2MSFTNGP12.phx.gbl…


>a worksheet is not a type of data but is an object: that’s all the
>difference
>
> you can type
> dim A as string
> but
> dim S as worksheet
> doesn’t mean anything because a sheet is not a type of data but is an
> object. So «new object» is the syntax.
>
> It’s just a syntax question: this makes you remember what your are
> edaling with, but also makes differences inside the VBA motor:
> creating a sheet is in memory creating many data (size, cells, colors,
> etc.) so the «set» (and not = ) means «launch the procedure to duplicate
> all the data of a sheet». It’s not one data, not an array of data but a
> whole structure of data.
>
> It’s usefull: the evidence is that it makes you think about the difference
> beteween a sheet and a string : one is an object


06-25-2005, 11:05 PM


#7

Re: Dim mySheet As New Worksheet

Vasant Nanavati a �crit :


> Not sure what you mean but your statement:
> is incorrect.

it’s not mathematics it’s human language
what i mean is explain after


06-26-2005, 12:05 AM


#8

Re: Dim mySheet As New Worksheet

OK, whatever you say! But I still don’t get it. Perhaps a language
interpretation problem.

Vasant

«abcd» <temp.nospamdc2@gmail.com> wrote in message
news:OBcYTpfeFHA.2556@TK2MSFTNGP10.phx.gbl…


>
>
> Vasant Nanavati a �crit :
>> Not sure what you mean but your statement:
>> is incorrect.

>
> it’s not mathematics it’s human language
> what i mean is explain after


06-26-2005, 12:05 AM


#9

Re: Dim mySheet As New Worksheet

I try something else:
you can say
h will be in meters
c will be in seconds

but saying
h will be a house
doesn’t mean anything (in this way of saying) because a house is not a unit.

But you can say «h» will be a short name for the house i’m building
and this «h» will have plenty of size, colors, timings (for building
it), etc. But a house is still not a unit.

the syntax dim … as … is supposed to mean
dim <variable> as <type of variable>

so , in this vba langage, saying s is a sheet does not mean anything:
a sheet is not a type of variable, it’s an object carrying plenty of
variables (called properties) but also methods (to build things)

it’s a «vba langage» choice:
we could decide we will write
dim s as sheet
because it’s easier: but it’s not the choosen way and the choosen way
permitt to remenber the difference between a unit and a house when just
seeing the shortname of it.


06-26-2005, 12:05 AM


#10

Re: Dim mySheet As New Worksheet

Again, I have to disagree. Of course, a worksheet is a composite object made
up of many components, but a string is also a composite data type made up of
many characters.

I guess I’m saying that:

Dim S As Worksheet

is a perfectly good VBA statement as well as perfectly good programming
practice.

Vasant

«abcd» <temp.nospamdc2@gmail.com> wrote in message
news:OYq6j7feFHA.2736@TK2MSFTNGP12.phx.gbl…


>I try something else:
> you can say
> h will be in meters
> c will be in seconds
>
> but saying
> h will be a house
> doesn’t mean anything (in this way of saying) because a house is not a
> unit.
>
> But you can say «h» will be a short name for the house i’m building
> and this «h» will have plenty of size, colors, timings (for building it),
> etc. But a house is still not a unit.
>
> the syntax dim … as … is supposed to mean
> dim <variable> as <type of variable>
>
> so , in this vba langage, saying s is a sheet does not mean anything:
> a sheet is not a type of variable, it’s an object carrying plenty of
> variables (called properties) but also methods (to build things)
>
> it’s a «vba langage» choice:
> we could decide we will write
> dim s as sheet
> because it’s easier: but it’s not the choosen way and the choosen way
> permitt to remenber the difference between a unit and a house when just
> seeing the shortname of it.


06-26-2005, 02:05 AM


#11

Re: Dim mySheet As New Worksheet

Thank you for taking time to try and understand what i mean and force me
to take care about words.

Some people say the difference between Einstein and other people was:
He was not wondering about details and mathematics like others. He was
looking for other (interesting) questions.
I’m not saying i’m Einstein. Just saying sometimes it’s better not to
read too much the details and choose the global point of view for the
opening it brings. ;-)
(the mathematics where written by his friend, and his end of life jobs
where not followed by people —they are today—)

Please, do try to allow me my other way of saying. My saying is wrong in
your (-sorry but- frozen) model. I understand what makes you sad. You
are right to say (and add after my writting) that vba is powerfull
enought to also permit a:
dim s as sheet
syntax and, ok, my writing can make think it’s forbidden to write this.
(I must choose a «does not mean what we expect because we need more to
create the sheet»)

I forgot words and look at ideas only: the syntax was juged «not enought
to do the job» because there’s not the same level between sheets and
strings and we do not want people to forgot this difference.

the difference between «as sheet» and «as new sheet» is explained at the
end of the
http://www.cpearson.com/excel/variables.htm
link given by Jim Cone

and i assume Frans (the asker) will also read it.

Even after the article you still must admit we do _not_ have a
dim T as new string
syntax (this is forbiden: vba doesn’t expect this kind of object after
new) here comes my answer.

Why not ? if «set / new» is so powerfull and save time, why not also
using it for strings ???

«do we really need a special ‘new’ syntax with sheets ?». That’s the way
i see the abyss of the question. (you’re right: going further and not
said a word to warn readers, so ? it’s me; human beeing, hello you … )
well, in fact you might say i’m an original guy; But that’s the
difference between vba and human talking.

My idea was here:
house (=plenty units and workers) versus unit
so «dim as sheet» does not mean the construct of the house…
because the vba syntax wish to distinguish them

Am i such raving mad ? Whatever: i don’t care it brings fun…
but if you read me more, you should be warn i’m an original one


06-26-2005, 06:05 AM


#12

Re: Dim mySheet As New Worksheet

Hi Jim,

Thanks for the link. I promise never to use the Dim … New any more.

But I am still puzzled by this Help-information (same text to be found in
MSDN). In short:
«After ‘Dim X As New worksheet’ you do not need a Set-command.»
I tried many ways but … niente.
Is this help a slip of the pen?

Frans

«Jim Cone» <jim.coneXXX@rcn.comXXX> wrote in message
news:ucgmKVeeFHA.228@TK2MSFTNGP12.phx.gbl…


> There is more information available here…
>
> Including: «Don’t Use The New Keyword In A Dim Statement»
> etc.


06-26-2005, 07:05 AM


#13

Re: Dim mySheet As New Worksheet

well, whatever is written, i tryed to test and chrono the both methods:
not such a difference (with worksheet in my test)
4% only if i loop a test: if S.name = «»
8% if the test is S is nothing

this �ean it depends on the action
but it’s not 200 times faster
using dim as new is not such a bad way
(it’s true one is better but… in real life the test will not be made
30000000 times and the few % is not enought to take real care of it all
day long, i think)

the test: lauch it and wait…
(on my computer win + excel 2000)

Private Declare Function GetTickCount Lib «kernel32» () As Long

Sub test()
Dim TM&, i&

Dim S As New Worksheet
Set S = Feuil1
Dim T As Worksheet
Set T = Feuil1

TM = GetTickCount ‘ chrono
For i = 1 To 30000000
If S.Name = «» Then: Beep
Next i
[A1] = GetTickCount — TM

TM = GetTickCount ‘ chrono
For i = 1 To 30000000
If T.Name = «» Then: Beep
Next i
[A2] = GetTickCount — TM

TM = GetTickCount ‘ chrono
For i = 1 To 30000000
If S Is Nothing Then: Beep
Next i
[B1] = GetTickCount — TM

TM = GetTickCount ‘ chrono
For i = 1 To 30000000
If T Is Nothing Then: Beep
Next i
[B2] = GetTickCount — TM

End Sub


06-26-2005, 11:05 AM


#14

Re: Dim mySheet As New Worksheet

Frans,

I believe it is a slip of the pen
I could not find the specific help reference you refer to,
but I did find this reference…

«…The New keyword
can’t be used to declare variables of any intrinsic data type,
can’t be used to declare instances of dependent objects, and
can�t be used with WithEvents.»

I have only found use for the ‘New’ word when creating a
Collection object (as Chip Pearson pointed out)
or when creating a new instance of an application, as in…
Dim appWord as Word.Application
Set appWord = New Word.Application

Regards,
Jim Cone
San Francisco, USA

«Frans van Zelm» <fhvzelm@hotmail.com> wrote in message
news:42be704e$0$764$3a628fcd@reader10.nntp.hccnet.nl…
Hi Jim,
Thanks for the link. I promise never to use the Dim … New any more.
But I am still puzzled by this Help-information (same text to be found in
MSDN). In short:
«After ‘Dim X As New worksheet’ you do not need a Set-command.»
I tried many ways but … niente.
Is this help a slip of the pen?
Frans

«Jim Cone» <jim.coneXXX@rcn.comXXX> wrote in message
news:ucgmKVeeFHA.228@TK2MSFTNGP12.phx.gbl…


> There is more information available here…
> Including: «Don’t Use The New Keyword In A Dim Statement»
> etc.


06-26-2005, 03:05 PM


#15

Re: Dim mySheet As New Worksheet

Dear Jim

So perhaps I am not that stupid after all. Thanks for your info.

Discussion closed, as far as I’m concearned.

Frans
«Jim Cone» <jim.coneXXX@rcn.comXXX> wrote in message
news:usTsVnleFHA.3040@TK2MSFTNGP14.phx.gbl…


> Frans,
>
> I believe it is a slip of the pen
> etc.


Обновление экрана

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

В начале:
Application.ScreenUpdating=false

в конце
Application.ScreenUpdating=true

Будьте уверены, чтобы восстановить настройки для Правда в конце макроса. Старая версия Excel будет автоматически восстанавливать настройки; Excel97 нет.

Простые объекты, а не составные объекты

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

Dim MyCell As Range
Set MyCell = Workbooks(«Book2»).Worksheets(«Sheet3»).Range(«C3»)
‘….
MyCell.Value = 123

По прямой ссылки на MyCell, VBA может получить доступ к объекту напрямую, а не решения полный путь к объекту каждый раз. Этот метод полезен только тогда, когда вы обращаетесь к объекту несколько раз в течение выполнения кода.

Конкретные декларации Тип объекта

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

Dim MySheet As Worksheet rather than
Dim MySheet As Object
Or
Dim NumRows As Long rather than
Dim NumRows As Variant

Это особенно верно с индексом переменных For Next петли, так как вариант типа должна быть пересмотрена каждой итерации цикла.

С заявлениями

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

With Worksheets(«Sheet1»).Range(«A1»)
.Font.Bold = True
.Value = 123
End With

Функции рабочего листа

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

MySum = Application.WorksheetFunction.Sum(Range(«A1:A100»))

а не

For Each C In Range(«A1:A100»)
MySum = MySum + C.Value
Next C

Понравилась статья? Поделить с друзьями:
  • Какое второе название имеет инструкция по техническому обслуживанию вагонов в эксплуатации
  • Каковы структура и содержание инструкций по охране труда
  • Какое будет значение i после исполнения инструкций запишите число
  • Какое будет значение i после исполнения инструкций i n 0 625
  • Какого типа должно быть выражение управляющее инструкцией switch