🍋

VBA文法

に公開
  • Sub プロシージャ
Sub test()

End Sub
  • Function 関数
Function Add(a As Integer, b As Integer) As Integer
  Add = a + b
End Function
  • 変数の宣言
Dim lasRow AsLong
Dim name As String
Dim age As Integer
Dim price As Double
  • シートを取得
Set ws = ThisWorkbook.Sheets("sheet name")
  • シートの最終行を取得
lastRow = ws.Cells(ws.Rows.Count,"A").End(xlUp).Row
  • For ループ
For i = 2 To lasRow

Next i
  • Do While ループ
Do While i < 10
   i = i + 1
Loop
  • For Each ループ
Dim cell As Range
For Each cell In Range("A1:A5")
    cell.Value = "OK"
Next cell
  • 指定列の値を取得
tableName = ws.Cells(i,3).Value
  • If 条件分岐
If x > 0 Then
   MsgBox "正の数"
ElseIf x < 0 Then
   MsgBox "負の数"
Else
   MsgBox "ゼロ"
End If
  • Select Case 構文
Select Case grade
   Case "A"
      MsgBox "優秀"
   Case "B"
       MsgBox "良好"
   Case Else
     MsgBox "頑張ってください"
End Select
  • 指定列に値を代入
ws.Cells(i,4).Value = "a"
  • vbCrLf 改行コード
MsgBox "第一行" & vbCrLf & "第二行"
  • デバッガー出力
Debug.Print "Successfully"
  • エラー処理
On Error GoTo ErrorHandler

Dim x As Integer
x = 10 / 0   ' エラー発生

Exit Sub

ErrorHandler:
    MsgBox "エラーが発生しました:" & Err.Description
  • 定数
定数 意味
xlUp 上方向
xlDown 下方向
xlToLeft 左方向
xlToRight 右方向
vbCrLf 改行コード
' 下方向に移動して最後の非空セルを選択
Range("A1").End(xlDown).Select

' 右方向に移動して最後の非空セルを選択
Range("A1").End(xlToRight).Select

' vbCrLf 改行コード
MsgBox "1行目" & vbCrLf & "2行目"
  • 主なデータ型
意味
Integer 整数(-32,768~32,767) Dim i As Integer
Long 長整数 Dim n As Long
Double 小数 Dim x As Double
String 文字列 Dim s As String
Boolean 真偽値 Dim flag As Boolean
Date 日付・時刻 Dim d As Date
Variant 任意型(自動的に型を判断) Dim v As Variant
LBound(arr) 配列の下限(最小インデックス) 0 或 1
UBound(arr) 配列の上限(最大インデックス) 如 5
  • 組み込み関数
関数 意味
Len(s) 文字列の長さを取得
Left(s, 2) 左から2文字を取得
Right(s, 2) 右から2文字を取得
Mid(s, 2, 3) 2文字目から3文字取得
UCase(s) 英字を大文字に変換
LCase(s) 英字を小文字に変換
LBound(arr) 配列の下限(最小インデックス)
UBound(arr) 配列の上限(最大インデックス)
IsArray() 配列かどうかを判定
Dim arr As Variant
arr = Array("Tokyo", "Osaka", "Nagoya")

MsgBox arr(0)   ' 出力:Tokyo
MsgBox arr(2)   ' 出力:Nagoya

'LBound(arr), UBound(arr)
Dim arr(1 To 5) As Integer
MsgBox LBound(arr) & " ~ " & UBound(arr)
' 出力:1 ~ 5

Discussion