2020年6月5日金曜日

[VBA] 04. 数値処理

整数、実数の処理とランダム値の生成方法についてまとめています。



整数化
小数の整数部分のみを返す関数には Int, Fix の2種類がある。違いは値が負の場合の処理。
Debug.Print Int(3.1415)
Debug.Print Fix(3.1415)
Debug.Print Int(-3.1415)
Debug.Print Fix(-3.1415)
実行結果
 3 
 3 
-4 
-3 


小数桁数の指定
Round 関数は指定した小数点以下の桁数に丸め込んだ数値を返す。四捨五入。

Round( expression [, numdecimalplaces ] )

Debug.Print Round(3.1415)
Debug.Print Round(3.1415, 0)
Debug.Print Round(3.1415, 1)
Debug.Print Round(3.1415, 2)
Debug.Print Round(3.1415, 3)
実行結果
   3 
 3 
 3.1 
 3.14 
 3.142 


絶対値
Abs 関数は負の数のマイナスを取り払う。

Round( expression [, numdecimalplaces ] )

Debug.Print Abs(-3.1415)
Debug.Print Abs(3.1415)
実行結果
   3.1415 
 3.1415 


ランダム値
ランダムな値を Single 型で返す。

Rnd[(number)]

numberの値 生成される値
指定なし
0 より大
シーケンス内の次の乱数
0 より小 number をシードとして使う毎回同じ値
0 と等しい 前回の生成値

Debug.Print Rnd(1)
Debug.Print Rnd(1)
Debug.Print Rnd
Debug.Print Rnd
Debug.Print
Debug.Print Rnd(-1)
Debug.Print Rnd(-1)
Debug.Print Rnd(-4)
Debug.Print Rnd(-4)
Debug.Print
Debug.Print Rnd(0)
Debug.Print Rnd(0)
実行結果
 8.386409E-02 
 6.711441E-02 
 0.660027 
 0.9407985 

 0.224007 
 0.224007 
 0.2133257 
 0.2133257 

 0.2133257 
 0.2133257 


数値の判定
数値かどうかを判定するには IsNumeric 関数を使用する。引数が数値と認識される場合は True, それ以外は False を返す。
Debug.Print IsNumeric(100)
Debug.Print IsNumeric("100")
Debug.Print IsNumeric("abc")

Debug.Print IsNumeric(100 * 2)
実行結果
True
True
False
True

尚、値が入っていないセルを IsNumeric 関数で判定すると True となる。値が入っていないセルを False としたい場合は、ワークシート関数の InNumber を使用する。

num = Range("A1")  'A1は値なし

Debug.Print IsNumeric(num)
Debug.Print WorksheetFunction.IsNumber(num)
実行結果
True
False

0 件のコメント:

コメントを投稿