Что такое dim visual basic
Dim statement (Visual Basic)
Declares and allocates storage space for one or more variables.
Syntax
Parts
Optional. Can be one of the following:
Optional. Specifies that these are object variables that refer to instances of a class that can raise events. See WithEvents.
Required. List of variables being declared in this statement.
Each variable has the following syntax and parts:
Part | Description |
---|---|
variablename | Required. Name of the variable. See Declared Element Names. |
boundslist | Optional. List of bounds of each dimension of an array variable. |
New | Optional. Creates a new instance of the class when the Dim statement runs. |
datatype | Optional. Data type of the variable. |
With | Optional. Introduces the object initializer list. |
propertyname | Optional. The name of a property in the class you are making an instance of. |
propinitializer | Required after propertyname =. The expression that is evaluated and assigned to the property name. |
initializer | Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created. |
Remarks
The Visual Basic compiler uses the Dim statement to determine the variable’s data type and other information, such as what code can access the variable. The following example declares a variable to hold an Integer value.
You can specify any data type or the name of an enumeration, structure, class, or interface.
You can declare a variable in a procedure, block, class, structure, or module. You cannot declare a variable in a source file, namespace, or interface. For more information, see Declaration Contexts and Default Access Levels.
A variable that is declared at module level, outside any procedure, is a member variable or field. Member variables are in scope throughout their class, structure, or module. A variable that is declared at procedure level is a local variable. Local variables are in scope only within their procedure or block.
If Option Explicit is on (the default), the compiler requires a declaration for every variable you use. For more information, see Option Explicit Statement.
Specifying an initial value
You can assign a value to a variable when it is created. For a value type, you use an initializer to supply an expression to be assigned to the variable. The expression must evaluate to a constant that can be calculated at compile time.
If an initializer is specified and a data type is not specified in an As clause, type inference is used to infer the data type from the initializer. In the following example, both num1 and num2 are strongly typed as integers. In the second declaration, type inference infers the type from the value 3.
Type inference applies at the procedure level. It does not apply outside a procedure in a class, structure, module, or interface. For more information about type inference, see Option Infer Statement and Local Type Inference.
For information about what happens when a data type or initializer is not specified, see Default Data Types and Values later in this topic.
You can use an object initializer to declare instances of named and anonymous types. The following code creates an instance of a Student class and uses an object initializer to initialize properties.
Declaring multiple variables
You can declare several variables in one declaration statement, specifying the variable name for each one, and following each array name with parentheses. Multiple variables are separated by commas.
If you declare more than one variable with one As clause, you cannot supply an initializer for that group of variables.
You can specify different data types for different variables by using a separate As clause for each variable you declare. Each variable takes the data type specified in the first As clause encountered after its variablename part.
Arrays
You can declare a variable to hold an array, which can hold multiple values. To specify that a variable holds an array, follow its variablename immediately with parentheses. For more information about arrays, see Arrays.
You can specify the lower and upper bound of each dimension of an array. To do this, include a boundslist inside the parentheses. For each dimension, the boundslist specifies the upper bound and optionally the lower bound. The lower bound is always zero, whether you specify it or not. Each index can vary from zero through its upper bound value.
The following two statements are equivalent. Each statement declares an array of 21 Integer elements. When you access the array, the index can vary from 0 through 20.
An array can have from 1 to 32 dimensions.
You can leave all the bounds blank in an array declaration. If you do this, the array has the number of dimensions you specify, but it is uninitialized. It has a value of Nothing until you initialize at least some of its elements. The Dim statement must specify bounds either for all dimensions or for no dimensions.
If the array has more than one dimension, you must include commas between the parentheses to indicate the number of dimensions.
You can initialize the values of an array by using an array literal. To do this, surround the initialization values with braces ( <> ).
For multidimensional arrays, the initialization for each separate dimension is enclosed in braces in the outer dimension. The elements are specified in row-major order.
For more information about array literals, see Arrays.
Default data types and values
The following table describes the results of various combinations of specifying the data type and initializer in a Dim statement.
If Option Strict is on, a compile-time error occurs.
If Option Infer is off and Option Strict is on, a compile-time error occurs.
If you specify a data type but do not specify an initializer, Visual Basic initializes the variable to the default value for its data type. The following table shows the default initialization values.
Each element of a structure is initialized as if it were a separate variable. If you declare the length of an array but do not initialize its elements, each element is initialized as if it were a separate variable.
Static local variable lifetime
Procedure declaration | Variable initialized | Variable stops existing |
---|---|---|
In a module | The first time the procedure is called | When your program stops execution |
In a class or structure, procedure is Shared | The first time the procedure is called either on a specific instance or on the class or structure itself | When your program stops execution |
In a class or structure, procedure isn’t Shared | The first time the procedure is called on a specific instance | When the instance is released for garbage collection (GC) |
Attributes and modifiers
You can apply attributes only to member variables, not to local variables. An attribute contributes information to the assembly’s metadata, which is not meaningful for temporary storage such as local variables.
Code outside a class, structure, or module must qualify a member variable’s name with the name of that class, structure, or module. Code outside a procedure or block cannot refer to any local variables within that procedure or block.
Releasing managed resources
If a class holds onto a particularly valuable and scarce resource (such as a database connection or file handle), you might not want to wait until the next garbage collection to clean up a class instance that’s no longer in use. A class may implement the IDisposable interface to provide a way to release resources before a garbage collection. A class that implements that interface exposes a Dispose method that can be called to force valuable resources to be released immediately.
The Using statement automates the process of acquiring a resource, executing a set of statements, and then disposing of the resource. However, the resource must implement the IDisposable interface. For more information, see Using Statement.
Example 1
The following example declares variables by using the Dim statement with various options.
Example 2
The following example lists the prime numbers between 1 and 30. The scope of local variables is described in code comments.
Example 3
In the following example, the speedValue variable is declared at the class level. The Private keyword is used to declare the variable. The variable can be accessed by any procedure in the Car class.
Dim statement
Declares variables and allocates storage space.
Syntax
The Dim statement syntax has these parts:
When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
The New keyword can’t be used to declare variables of any intrinsic data type or to declare instances of dependent objects, and it can’t be used with WithEvents.
Remarks
Variables declared with Dim at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure.
Use the Dim statement at the module or procedure level to declare the data type of a variable. For example, the following statement declares a variable as an Integer.
Also use a Dim statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet.
If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object by using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn’t refer to any particular instance of an object.
You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.
If you don’t specify a data type or object type, and there is no Def_type_ statement in the module, the variable is Variant by default. When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string («»), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.
When you use the Dim statement in a procedure, you generally put the Dim statement at the beginning of the procedure.
Example
This example shows the Dim statement used to declare variables. It also shows the Dim statement used to declare arrays. The default lower bound for array subscripts is 0 and can be overridden at the module level by using the Option Base statement.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Что означает DIM в Visual Basic и BASIC?
Что означает DIM в Visual Basic?
10 ответов
Dim первоначально (в BASIC) означало размер, поскольку он использовался для определения размеров массива.
(первоначальная реализация BASIC была Dartmouth BASIC, которая произошла от FORTRAN, где размерность прописана.)
В настоящее время Dim используется для определения любой переменной, а не только массивов, поэтому ее значение больше не интуитивно.
Dim имел различные значения, приписываемые ему.
я нашел ссылки о Dim смысл «Объявить В Памяти», более уместной ссылкой является документ на Дим Заявление опубликовано Oracle как часть ссылки на язык Siebel VB. Конечно, вы можете утверждать, что если вы не объявляете переменные в памяти, где вы это делаете? Может быть!—23—>»объявить в модуле» является хорошей альтернативой, учитывая, как Dim is используемый.
действительно, Не Важно? Я имею в виду, это ключевое слово, которое имеет свой смысл внутри искусственного языка. Это не должно быть слово в английском или любом другом естественном язык. Так что это может означать все, что вы хотите, важно только то, что это работает.
Dim. К моему разочарованию, они не говорят, что значит Dim стоять, и только сказать, как он используется.
но прежде чем моя надежда была тусклой, мне удалось найти это система микрокомпьютер Би-би-си, используемых руководство (который утверждает, что с 1984 года, и я не хочу сомневаться в этом). Микрокомпьютер Би-би-си используется вариант BASIC под названием BBC BASIC и он описан в документе. Хотя в нем не сказано, что делает Dim стоим, он говорит (на стр. 104):
. вы можете измерить N$, чтобы иметь столько записей, сколько хотите. Для например, DIM N$(1000) создаст строковый массив с пространством для 1000 различные наименования.
как я уже сказал, это не говорит, что Dim означает размерность, но служит доказательством того, что связывание Dim С Dimension было обычным делом на момент написания этого документа.
теперь я получил полезный сюрприз позже (на странице 208), название раздела, который описывает ключевое слово DIM (Примечание: это не указано в содержимом), говорит:
перед использованием массива его необходимо определить в инструкции DIM (dimension).
вы можете найти это в рамках True BASIC Online руководства пользователя на веб-странице True BASIC inc, компании, основанной Томас Курц Евгений, соавтор BASIC.
так, в reallity, Dim это сокращение для DIMENSION и да. То, что существовало в Фортране раньше, поэтому вполне вероятно, что оно было выбрано влиянием Фортрана как Патрик Макдональд сказал в своем ответе.
это сокращение от Dimension, поскольку оно изначально использовалось в BASIC для указания размера массивов.
часть исходного исходного кода базового компилятора, где он будет прыгать при поиске DIM команда, в которой вы можете четко видеть исходное намерение для ключевого слова:
позже он стал использоваться для объявления всех видов переменных, когда возможность указать тип для переменных была добавлена в более поздних реализациях.
измерение переменной, в основном вы говорите компилятору, что вам понадобится переменная этого типа в какой-то момент.
он означает размер, но обычно читается как «создать переменную» или » выделить пространство для этого.»
переменной. Первоначально это было сокращенно от «dimension», который не является термином, который используется в программировании (за пределами этого конкретного ключевого слова) в какой-либо значительной степени.
DIM означает объявление в памяти DIM x как новое целое число создает пространство в памяти, где хранится переменная x
назад в день тусклой зарезервированной памяти для массива, и когда память была ограничена, вы должны были быть осторожны, как вы ее использовали. Однажды я написал (в 1981 году) базовую программу на TRS-80 Model III с 48KB RAM. Он не будет работать на аналогичной машине с ОЗУ 16Kb, пока я не уменьшу размер массива, изменив оператор DIM
сокращение от размерности. Это тип переменной. Вы объявляете (или» сообщаете » Visual Basic), что настраиваете переменную с этим словом.
ключевое слово Dim является необязательным, когда мы используем его с модификаторами-Public, Protected, Friend,Protected Friend,Private,Shared,Shadows,Static, ReadOnly и т. д. например: Static nTotal As Integer
оператор Dim можно использовать без типа данных при установке опция выводить на. В этом случае компилятор выводит тип данных переменная от типа ее выражения инициализации. Пример :
приведенное выше утверждение эквивалентно- Dim nExpVar As Integer
VBA Dim
Excel VBA Dim
DIM в VBA можно назвать, так как он объявляет переменную в различных типах данных, таких как целочисленная логическая строка или double и т. Д. В любом языке программирования переменная должна быть объявлена определенному типу данных, например, X является переменной, и если мы определяем X как целое число, которое означает, что мы можем хранить целочисленные значения в X. Теперь, если мы объявим Y как строку, это означает, что мы можем хранить строковые значения в Y.
Как обсуждалось выше, DIM в VBA используется для объявления переменных разных типов данных. Но что такое DIM в VBA? DIM означает измерение или объявить в памяти в VBA. Мы объявляем переменную для определенного типа данных в VBA, мы используем ключевое слово DIM, чтобы сделать это. Мы можем использовать структуры классов, уже встроенные в VBA, или сами можем создать новую. Чтобы дать очень простое объяснение DIM, мы можем взять это в качестве примера, например, нам нужно хранить логические значения в переменной. Логические значения означают, что они либо истинны, либо ложны. Теперь логические значения, как мы знаем, являются логическими в типах данных, поэтому нам нужно объявить нашу переменную в логическом типе данных.
Если мы говорим, что переменная X должна хранить значение в логическом значении, нам нужно объявить X как логическую переменную, чтобы она могла хранить желаемый тип данных.
Использование DIM с синтаксисом в VBA выглядит следующим образом:
Переменная DIM As DataType.
Когда мы пытаемся определить конкретный тип данных, Excel предварительно вводит его для нас.
Посмотрите на скриншот ниже,
Excel определяет по ключевым словам, которые мы вводим, и отображает возможные типы данных, которые мы могли бы использовать.
Как использовать VBA Dim в Excel?
Мы научимся использовать VBA Dim на нескольких примерах в Excel.
Во-первых, давайте использовать Integer в качестве типа данных для объявления. Мы будем использовать три переменные и объявим каждую из них как целые числа, используя ключевое слово DIM. И тогда мы будем отображать окончательный результат.
Подсказка. Чтобы использовать VBA в Excel, нам нужно включить доступ для разработчиков с помощью учетной записи на вкладке «Файл».
Шаг 1. Перейдите на вкладку « Разработчик » и щелкните Visual Basic, чтобы открыть редактор VBA.
Шаг 2: В окне проекта нажмите на лист 1, чтобы открыть окно кода.
Шаг 3: Когда откроется окно кода, чтобы объявить подфункцию, чтобы начать писать код.
Шаг 4: Объявите три переменные A, B и C как целые числа.
Шаг 5: присвойте этим трем переменным любые случайные значения.
Шаг 6: Показать значения C с помощью функции msgbox.
Шаг 7: Запустите код с помощью кнопки запуска. Как только мы запустим код, мы получим следующий результат в качестве вывода.
Шаг 8: Поскольку A, B и C были объявлены как целое число, а сумма A и B также является целым числом, может отображаться значение, сохраненное в C. Но если мы изменим значение C = A / B, как показано на скриншоте ниже.
Шаг 9: Теперь давайте снова запустим код и посмотрим, что мы получим в результате,
В результате мы получаем ноль, но 5/10 равен 0, 5, а не 0. Это потому, что C может хранить только целые значения, а не значения после десятичной дроби.
В предыдущем примере мы видели, что если значение результата в C находится в десятичных числах, значения после десятичных чисел не отображаются в выходных данных, потому что мы объявили C как целое число. Теперь мы будем использовать другой тип данных для объявления из функции DIM для отображения исходного значения C.
Шаг 1. Перейдите на вкладку « Разработчик » и щелкните Visual Basic, чтобы открыть редактор VBA.
Шаг 2: В окне проекта нажмите на Лист 2, чтобы открыть окно кода.
Шаг 3: Как только окно кода открыто, создайте подфункцию, чтобы начать писать код.
Шаг 4: Объявите три переменные AB и C. Объявите A и B как целые числа, а C как двойные.
Шаг 5: Аналогично примеру 1 присвойте значения этим переменным.
Шаг 6: Теперь отобразите вывод с помощью функции msgbox.
Шаг 7: Запустите код с кнопки запуска. Запустив код, мы получим следующий результат:
Теперь у нас есть точное значение C, которое составляет 0, 5.
Давайте использовать функцию DIM для хранения символов означает строки.
Шаг 1. Перейдите на вкладку « Разработчик » и щелкните Visual Basic, чтобы открыть редактор VBA.
Шаг 2: В окне проекта нажмите на Лист 3, чтобы открыть окно кода.
Шаг 3: Создайте подфункцию, чтобы начать писать код,
Шаг 4: Объявите переменную A как строку,
Шаг 5: Присвойте любые случайные значения A,
Шаг 6: Показать вывод с помощью функции msgbox.
Шаг 7: Запустите код из предоставленной кнопки запуска и посмотрите результат,
Объяснение VBA DIM
DIM в VBA используется для объявления переменных как различных типов данных. Переменные могут быть единственной переменной или массивом, который мы должны иметь в виду, чтобы объявить правильный тип данных для получения правильного вывода.
Например, если наши выходные данные будут в String, нам нужно объявить переменную в String, а если выходные данные будут в десятичных числах, то объявить переменную как double и т. Д.
То, что нужно запомнить
Есть несколько вещей, которые мы должны помнить о DIM в VBA: