在公式中使用變數之前,必須先進行宣告。變數可以保留指定型別的資料值。允許的資料型別包括七種簡單型別 (數值、貨幣、字串、布林、日期、時間和日期時間) 及六種範圍型別 (數值範圍、貨幣範圍、字串範圍、日期範圍、時間範圍及日期時間範圍) 以及之前提到可以保留陣列的資料型別。所以變數一共可以使用 26 種不同的資料型別。
當您宣告變數時,必須先為其指定一個名稱。變數的名稱不能與任何 Basic 語法中有效的函式、運算子名稱或其他關鍵字相同。例如,變數名稱不可以取為 Sin、Mod 或 If,因為 Sin 是內建函式,Mod 是內建運算子,而 If 是內建關鍵字。在公式編輯器中輸入公式時,內建的函式、運算子的名稱和其他關鍵字均會以不同的顏色加以醒目提示。可較易檢查出變數的名稱是否會造成衝突。
變數宣告完之後,就可以在公式中使用。例如,您也許想要為它指派起始值:
Dim x As Number 'Declare x to be a Number variable x = 10 'Assign the value of 10 to x
每個陳述式可宣告一個以上的變數,中間以逗號區隔:
Dim x As Number, y as String, z as DateTime Range x = 10 : y = "hello" z = #Jan 1, 1999# To #Jan 31, 1999#
大致而言,在宣告變數時,並不需要明確指定其型別。在這種情況下,變數的型別是由其第一個指派來決定。這與 Formula 特殊變數類似。它與 Visual Basic 不同。在 Visual Basic 中,宣告時沒有指定型別的變數會自動指定為 Variant 型別。然而,在實際應用時,這表示您可以像使用 Visual Basic 的 Variant 一樣地寫公式。
Dim p 'The type of p is not known yet p = "bye" 'The type of p is now set to be String Dim q 'The type of q is not known yet q = Array ("hello", p) 'q is a String Array 'Error- p is a String variable and cannot hold a Number p = 25 Dim r 'r is a Number variable, and holds the value 5 r = (10 + 5) / 3 'The types of a and c are not known yet Dim a, b As Boolean, c b = False 'The type of a is now set to Boolean 'and its value is False a = b 'The type of c is now set to Number and its value is 17 c = 2 + 3 * 5
宣告與初始化範圍變數的範例
Dim gradeA, quarter 'The type of gradeA is set to Number Range gradeA = 90 To 100 'The type of quarter is set to Date Range quarter = CDate (1999, 10, 1) To CDate (1999, 12, 31)