プログラミング系のネタをまとめていきます。

変数


Dim 変数名 As データ型
Integer整数型2byte
Long長整数型4byte
Single単精度小数4byte
Double倍精度小数8byte
Currency通貨型8byte
String文字列2byte (1文字?)
Date日付型8byte
Objectオブジェクト型4byte
Variantバリアント型16byte
Boolean真偽値2byte

文字列の長さ制限


Dim B As String * 10 ' 10文字に限定

グローバル定数


Private Const CONST_VAL_0 = 10
Public Const CONST_VAL_1 = 20	' Public 定数は宣言できないっぽい。エラーになる。

Const CONST_STR As String = "文字列定数"

列挙型


Public Enum ParamType
    None = 0
    TypeInt = 1
    TypeStr = 2
End Enum

Null関連

vbNullStringString型の初期値
EmptyVariant型の初期値。何も値が入っていない状態。
Null
(vbNull)
Variant型に格納できる特殊な値。
Nothingオブジェクト変数の初期値

Empty


Dim myVar As Variant
Debug.Print VarType(myVar)   '--> 0(定数vbEmpty)と表示される
Debug.Print TypeName(myVar)  '--> Empty と表示される
Debug.Print IsEmpty(myVar)   '--> True と表示される

Dim myVar As Variant                    '初期値はEmpty
If myVar = 0 Then Debug.Print "True"    '--> True と表示される
If myVar = "" Then Debug.Print "True"   '--> True と表示される

Null


Dim myVar As Variant        '初期値はEmpty
myVar = Null                'Nullを代入
Debug.Print VarType(myVar)  '--> 1(定数vbNull)と表示される
Debug.Print TypeName(myVar) '--> Null と表示される
Debug.Print IsNull(myVar)   '--> True と表示される

Nothing


オブジェクトの初期状態を判定して処理する。
If myObj Is Nothing Then
    Set myObj = Forms![フォーム1]
End If

演算子

除算

演算子演算
/(半角)結果はDouble3/2 → 1.5
1/3 → 0.3333...
¥(半角)4/3 → 1
4/5 → 0
Mod余り7 Mod 4 → 3
3 Mod 4 → 3
注意点

VBはDoubleをIntegerに代入する際、四捨五入されます。
そのため、次のような計算をする際は注意が必要です。
Dim valA As Integer
Dim valB As Integer
Dim valC As Integer
valA = 3
valB = 2
valC = valA / valB  'valC = 2 となる

三項演算子


Dim str As String
Dim a As Integer, b As Integer

a = 3
b = 1
str = IIf(a > b, "大きい", "等しいか小さい")
MsgBox str

構造体


Type Point
    x As Long
    y As Long
End Type

関数

返り値呼び出し
Sub無しCall Subプロシージャ
Functionあり(Call) Functionプロシージャ

Subプロシージャ


Sub Test()
	Dim str As String
	str = "text"
	Call SubTest(str)
End Sub

Sub SubText(str As String)
	MsgBox "テキスト : " + str
End Sub

プロシージャの途中でリターンするときは、Exit Subを使う。

Functionプロシージャ


Call ステートメントでの呼び出しも可能。

Sub Test()
	Dim v As Integer
	v = FuncAdd(10, 20)
End Sub

Function FuncAdd(a As Integer, b As Integer) As Integer
	FuncAdd = a + b		' 計算結果を返す
End Function

プロシージャの途中でリターンするときは、Exit Functionを使う。

引数の参照渡し

ByVal値渡し指定しない場合はこれ
ByRef参照渡し呼び出し元の変数を関数内で変更できる

Sub Test()
	Dim str As String
	str = "text"
	Call Func(str)
End Sub

Sub Func(ByRef a As String)
   a = "suzuki"         ' 受け取った値を書き換える
End Sub

TextBoxを引数として渡す


Sub TestFunc(textBox As MSForms.textBox)
    textBox.Text = "text"
End Sub

基本処理

文字列→数値変換


Dim a As String
Dim v As Integer
a = "123"
v = val(a)

数値→文字列変換


Dim a As Integer
Dim t As String
a = 123
t = str(a)

文字列比較

同値判定

If ActiveCell.Value = "text" Then
	MsgBox "等しい"
Else
	MsgBox "等しくない"
End If

If ActiveCell.Value <> "text" Then
	MsgBox "等しくない"
Else
	MsgBox "等しい"
End If
文字列が含まれているかどうか

If InStr(ActiveCell.Value, "text") > 0 Then
	MsgBox "含まれている"
Else
	MsgBox "含まれていない"
End If

パターンマッチ

Like、「*」、「?」 を使って判定する。

' abc, xyz の間に任意の文字列が入ってもOK
If ActiveCell.Value Like "abc*xyz" Then	'

' 1〜5で始まる文字列
If ActiveCell.Value Like "[1-5]*" Then

' 都道府県名のうち、北海道、東京都、神奈川県、和歌山県、鹿児島県 以外がtrueになる
If Not c.Value Like "??[県府]" Then

文字列操作関数の$記号


文字列操作関数には最後に$記号を付けられるものがあります。
$記号なし返り値は Variant型
$記号あり返り値は String型戻り値の方が決まっているので、処理速度が速い

例
Left(str As String, length As Long)
Left$(str As String, length As Long) As String

コレクション、動的配列

可変長リスト


Dim list As Collection
Set list = New Collection

' listに要素を追加する
Dim col As Integer
col = 1
Do While ActiveSheet.Cells(1, col) <> ""
	list.Add ActiveSheet.CelllS(1, col)
	col = col + 1
Loop

' リストの要素を順に処理する
Dim str As String
str = ""
For Each v In list
	str = str & v.Value
Next

Dictitonary


Dim dict As Scripting.Dictionary
Set dict = CreateObject("Scripting.Dictionary")

dict.Add "A1", ActiveSheet.Cells("A1")
dict.Add "A2", ActiveSheet.Cells("A2")
dict.Add "A3", ActiveSheet.Cells("A3")

Dim key As Variant
For Each key In dict.Keys
	Debug.Print key, dict(key).Value
Next

クラスモジュール


C++やJavaのクラスに当たるもの。

作り方


Visual Basic Editor(VBE)の [挿入] - [クラスモジュール] で新規作成。
追加されたクラスモジュールを選択して、プロパティの (オブジェクト名)で名前変更。


●TestClass
Private v0 As Integer
Private v1 As Integer

Public Sub SetParam(a As Integer, b As Integer)
    v0 = a
    v1 = b
End Sub

Public Sub Output()
    MsgBox "add : " & (v0 + v1) & vbCrLf & "sub : " & (v0 - v1)
End Sub


●呼び出し
Dim testClass As TestClass
Set testClass = new TestClass

Call testClass.SetParam(10, 20)
Call testClass.Output

Menu

メインコンテンツ

プログラミング

機器

Macツール

各種情報

Wiki内検索

おまかせリンク

Androidアプリ

AdSense

技術書


管理人/副管理人のみ編集できます