VBA算術運算子

2019-10-16 23:12:59

以下是VBA支援算術運算子。

假設變數A=5,變數B=10,那麼 -

運算子 描述 範例
+ 兩個運算元相加 A + B = 15
- 兩個運算元相減 A - B = -5
* 兩個運算元相乘 A * B = 50
/ 兩個運算元相除 B / A = 2
% 模運算子,整數除法後的餘數 B % A = 0
^ 指數運算子 B ^ A = 100000

範例

新增一個按鈕並嘗試下面的範例來了解如何在VBA中使用算術運算子。

Private Sub Constant_demo_Click()
   Dim a As Integer
   a = 5

   Dim b As Integer
   b = 10

   Dim c As Double

   c = a + b
   MsgBox ("Addition Result is " & c)

   c = a - b
   MsgBox ("Subtraction Result is " & c)

   c = a * b
   MsgBox ("Multiplication Result is " & c)

   c = b / a
   MsgBox ("Division Result is " & c)

   c = b Mod a
   MsgBox ("Modulus Result is " & c)

   c = b ^ a
   MsgBox ("Exponentiation Result is " & c)
End Sub

當點選按鈕或執行上面的指令碼時,會產生類似下面的結果。

Addition Result is 15

Subtraction Result is -5

Multiplication Result is 50

Division Result is 2

Modulus Result is 0

Exponentiation Result is 100000