要執行程式時,必須先將程式和資料載入到電腦的主記憶體中才能執行,但是程式中所要的資料是如何放入記憶體呢﹖在大多數的高階語言都是使用變數,其方法是當你在設計程式時,將每個資料給予一個變數名稱,再對該變數給予初值,也就是說在程式用到該資料的地方,以對應的變數名稱取代該資料即可。當程式編譯成可執行檔時,電腦便自動在主記憶體保留一個位置來存放該變數。
變數的命名規則
Visual Basic提供了一些有關變數的命名規則,編寫程式時必須遵守變數的命名規則,這些規則如下:
1.
一個變數名稱不能超過255個字元。
2.
變數名稱第一個字元是字母(A-Z),大小寫均可或中文名稱。除第一個字元外,其它字元可以為A-z、a-z、0-9或_等字元,建議少用中文名稱。
3.
變數名稱最後一個字元可用型態宣告字元:%、&、!、#、@、$等符號來代表該變數的資料型態。建議不要使用,這是早期BASIC為初學者方便而設計。
4.
變數名稱不可以是Visual Basic的保留字。所謂「保留字」(Reserved
Word)是指Visual Basic系統所提供的屬性(Property)、事件(Event)、方法(Method)、運算子(Operator)、敘述(Statement)、和函數(Function)等所使用的文字或運算符號。
5.
變數名稱中的英文字母是大小寫不分的。例如:SCORE、Score、score三者均代表同一個變數。
6.
變數的命名最好具有意義、名稱最好和資料有關係,如此在程式中不但可讀性高而且易記。例如:變數名稱salary、total分別代表薪資及總數。
7.
變數名稱有多個單字時,中間可以加上底線"_",以增加變數名稱的可讀性。例如:Tel_No代表電話號碼,ID_No代表身份証號碼。
8.
若變數未設定初值時,數值變數的預設值為0;字串變數的預設值為空字串。
各種變數的長度
為了要防止變數佔用太多的主記憶體,Visual Basic視資料的大小與資料種類而給予不同的資料型態。各類資料型態所佔用的位元數(Bytes)是不相同,各種變數的長度請參考以下的數據種類表。
Data type |
Storage size |
Range |
Byte |
1 byte |
0 to 255 |
Boolean |
2 bytes |
True
or False |
Integer |
2 bytes |
-32,768 to 32,767 |
Long (long integer) |
4 bytes |
-2,147,483,648 to 2,147,483,647 |
Single |
4 bytes |
-3.402823E38 to -1.401298E-45 for negative
values; 1.401298E-45 to 3.402823E38 for positive values |
Double |
8 bytes |
-1.79769313486232E308 to |
Currency |
8 bytes |
-922,337,203,685,477.5808 to
922,337,203,685,477.5807 |
Decimal |
14 bytes |
+/-79,228,162,514,264,337,593,543,950,335
with no decimal point; smallest non-zero number is |
Date |
8 bytes |
January 1, 100 to December 31, 9999 |
Object |
4 bytes |
Any Object reference |
String |
10 bytes + string length |
0 to approximately 2 billion |
String |
Length of string |
1 to approximately 65,400 |
Variant |
16 bytes |
Any numeric value up to the range of a Double |
Variant |
22 bytes + string length |
Same range as for variable-length String |
User-defined |
Number required by elements |
The range of each element is the same as
the range of its data type. |
Note:
1.Arrays
of any data type require 20 bytes of memory plus 4 bytes for each array
dimension plus the number of bytes occupied by the data itself. The memory
occupied by the data can be calculated by multiplying the number of data
elements by the size of each element. For example, the data in a
single-dimension array consisting of 4
2.Integer
data elements of 2 bytes each occupies 8 bytes. The 8 bytes required for the
data plus the 24 bytes of overhead brings the total memory requirement for the
array to 32 bytes.
3.A Variant containing an array requires 12 bytes more than the array alone.