Excel VBAとは

  • 概要
    • Excelを自動化するためのプログラミング言語
  • 知識
    • Excel
  • 用語
    • ワークブック>ワークシート>セル
  • オブジェクト(ワークブック、ワークシート、セル)
    • プロパティ(属性)
    • メソッド(処理)

Visual Basic Editorを使おう

  • Visual Basic Editorを開く
    • 開発>Visual Basic
    • プロパティウィンドウ、ツールバーを表示させる
  • 新規プロジェクト作成
    • 挿入>標準モジュール

はじめてのExcel VBA

  • Hello Worldを表示させる
    • 「HelloWorld」はプロシージャ名
Sub HelloWorld()
 MsgBox ("hello world")
End Sub
  • Editor上のみで改行する場合
MsgBox _
("hello world")
  • コメントを挿入(シングルクォーテーションを使用)
'コメント

セルに値を表示してみよう

Sub CellChange()
 Worksheets("Sheet1").Range("A1").Value = "hello"
 Range("A2").Value = "hello2" 'アクティブなシートは指定省略可能
 Cells(3, 1).Value = "hello3" '行列番号で指定
 Cells(3, 1).Offset(1, 0).Value = "hello4" '相対位置を指定
End Sub

複数のセルに値を表示してみよう

Sub CellsChange()
 Range("A1", "B3").Value = "hello" 'A1-B3まで表示
 Range("A5:C7").Value = "hello2" 'A5-C7まで表示
 Range("4:4").Value = "row 4" '4行目に表示
 Range("C:C").Value = "Column C" 'C列目に表示
 Cells.Clear '値を全てクリア
End Sub

Withで命令をまとめてみよう

  • オブジェクトにプロパティを設定する
Sub WithTest()
 Range("A1").Value = "hello"
 Range("A1").Font.Bold = True '文字を太字に設定
 Range("A1").Font.Size = 16 '文字サイズを16に設定
 Range("A1").Interior.Color = vbRed 'セルの背景色を赤に設定
End Sub
  • 上記のプロシージャをWithステートメントでまとめる
Sub WithTest2()
 With Range("A2")
  .Value = "hello"
  With .Font
   .Bold = True '文字を太字に設定
   .Size = 16 '文字サイズを16に設定
  End With
  .Interior.Color = vbRed 'セルの背景色を赤に設定
 End With
End Sub

セルの値を取得してみよう

Sub GetTest()
 MsgBox Range("A1").Value 'A1の値を取得し表示
 MsgBox (Range("A1").Font.Size) 'A1の文字サイズの値を取得し表示
End Sub

メソッドを使ってみよう

Sub MethodTest()
 'Range("B2").Clear
 'Range("B5").Delete shift:=xlShiftUp 'B5を削除し上方向にシフト
 Worksheets.Add after:=Worksheets("Sheet2"), Count:=2 'Sheet2の後にシートを2枚追加
End Sub

Excel VBAとマクロの関係

  • VBAとマクロは表裏一体
    • VBAで記述した処理は自動的にExcelのマクロとして登録される
    • マクロの記録を実行するとExcel側で自動的にVBAのコードが生成される

Integer型の変数を使ってみよう

Sub VaiableTest()
 
 Dim x As Integer 'Integer型の変数名xを宣言
 x = 10 + 5
 x = x + 1
 
 '四則演算
 '+ - / *
 '商,余
 '\ mod
 'べき乗
 '^
 x = 2 ^ 3
 
 'Range("A1").Value = x
 Debug.Print x 'イミディエイトウィンドウに表示

End Sub
  • イミディエイトウィンドウは値を確認したい時などデバグ時に有用

他データ型の変数を使ってみよう

Sub VariableTest()

 Dim y As Double '実数
 Dim s As String '文字列
 Dim d As Date '日付
 Dim z As Variant '宣言時は型を決定しない
 Dim f As Boolean '真偽値
 Dim r As Range 'Rangeオブジェクト
 
 y = 19.5
 s = "hello"
 d = "2012/04/23"
 f = True
 Set r = Range("A1")
 
 Debug.Print y / 3
 Debug.Print s & "world"
 r.Value = d + 7 'dに7日間追加

End Sub

配列を使ってみよう

  • 記述法1
Sub VariableTest()
 
 'sales_0 = 200
 'sales_1 = 150
 'sales_2 = 300
 
 Dim sales(2) As Integer
 sales(0) = 200
 sales(1) = 150
 sales(2) = 300
 
 Debug.Print sales(1)
 
End Sub
  • 記述法2
Sub VariableTest2()

 Dim sales As Variant
 sales = Array(200, 150, 300)
 Debug.Print sales(2)
  
End Sub

Ifで条件分岐をしてみよう

Sub IfTest()

 ' = < > <= >= <> and not or
 If Range("a1").Value > 80 Then
  Range("a2").Value = "OK!"
 ElseIf Range("a1").Value > 60 Then
  Range("a2").Value = "soso..."
 Else
  Range("a2").Value = "NG!"
 End If

End Sub

Selectで条件分岐をしてみよう

Sub SeletTest()

 Dim signal As String
 signal = Range("a1").Value
 
 Dim result As Range
 Set result = Range("a2")
 
 Select Case signal
 
 Case "red"
  result.Value = "STOP"

 Case "green"
  result.Value = "GO!"

 Case "yellow"
  result.Value = "CAUTION!"

 Case Else
  result.Value = "n.a."

 End Select

End Sub

While/Forでループ処理をしてみよう

  • While文
Sub WhileTest()

 'A1-A9に1-9の値を挿入
 Dim i As Integer
 i = 1
 
 Do While i < 10
  Cells(i, 1).Value = i
  i = i + 1
 Loop

End Sub
  • For文
Sub ForTest()

 Dim i As Integer
 
 For i = 1 To 9
  Cells(i, 1).Value = i
 Next i

End Sub
  • For文にてStepを利用すると間隔を空けて表示さることが可能
For i = 1 To 9 Step 2

Eachで配列のループ処理をしてみよう

Sub EachTest()
 Dim names As Variant
 names = Array("taguchi", "fkoji", "dotinstall")
 
 For Each Name In names 'namesから1つずつ取り出してNamesに保存
  Debug.Print Name
 Next Name

End Sub

Callでプロシージャを呼びだそう

Sub CallTest()

 Dim names As Variant
 names = Array("taguchi", "fkoji", "dotinstall")
 
 For Each name In names
  Call SayHi(name)
 Next name

End Sub
  • CallTetプロシージャを別プロシージャから呼び出す
Sub SayHi(ByVal name As String)
 Debug.Print "hi!," & name
End Sub
  • イミディエイト
hi!,taguchi
hi!,fkoji
hi!,dotinstall

Functionプロシージャを使ってみよう

  • Subプロシージャ
    • 返り値を返さない
  • Functionプロシージャ
    • 返り値を返す
  • 呼び出し元
Sub CallTest()

 Dim names As Variant
 names = Array("taguchi", "fkoji", "dotinstall")
 
 For Each name In names
  Debug.Print SayHi(name)
 Next name

End Sub
  • 呼び出し側
Function SayHi(ByVal name As String)
 SayHi = "hi!," & name
End Function
  • イミディエイト
hi!,taguchi
hi!,fkoji
hi!,dotinstall

成績表を処理してみよう

  • 名前とスコアの一覧表をExcelに入力(A1-10,B1-10)
  • 基準より低い点数をにハイライト設定しその数を集計を行う
Sub FindLowScores()

 Dim i As Long 'LongはIntegerより桁数の大きい数値を扱える
 Dim n As Long
 i = 2
 n = 0
 
 Do While Cells(i, 1).Value <> "" '値が空ではない場合
  If Cells(i, 2).Value < 60 Then
   Cells(i, 2).Interior.Color = vbRed
   n = n + 1
  End If
  i = i + 1
 Loop
 
 MsgBox (n & "件該当しました!")

End Sub

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2013-08-10 (土) 01:54:00 (3911d)