この記事で解決できる悩み
✅ CreateObjectの使い方が分からない
✅ 参照設定との違いが分からない
✅ FileSystemObjectやDictionaryの使い方が知りたい
✅ エラー429「オブジェクトを作成できません」が出る
✅ 遅延バインディングと早期バインディングの使い分けが分からない
✅ Excel・Word・IEを外部操作したい
この記事を読むと…
- CreateObjectの基本構文と使い方が完璧に理解できる
- 参照設定との違いとメリット・デメリットが分かる
- 実例コード20個でFileSystemObject・Dictionary・ADODBの使い方を習得
- エラー429の原因と対処法が分かる
- Excel・Word・IEの外部操作ができるようになる
CreateObjectとは?3分で基本を理解
CreateObjectの役割
CreateObjectは、外部のCOMオブジェクト(ActiveXコンポーネント)を実行時に生成するVBA関数です。
これにより、以下のような外部ライブラリやアプリケーションをVBAから操作できます。
| 用途 | オブジェクト名 | 主な機能 |
|---|---|---|
| ファイル操作 | Scripting.FileSystemObject | ファイル・フォルダの作成・削除・コピー |
| 連想配列 | Scripting.Dictionary | キーと値のペアでデータ管理 |
| データベース | ADODB.Connection | SQL Server・Access接続 |
| Excel操作 | Excel.Application | 別のExcelファイルを操作 |
| Word操作 | Word.Application | Wordファイルを操作 |
| IE操作 | InternetExplorer.Application | Webスクレイピング |
CreateObjectの基本構文
Set オブジェクト変数 = CreateObject("プログラムID")
重要ポイント:
- 必ず
Setステートメントを使う - プログラムIDは文字列で指定
- オブジェクト変数は
Object型またはVariant型で宣言
実例1: FileSystemObjectの基本
Sub CreateFSOExample()
'FileSystemObjectを作成
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
'ファイルが存在するか確認
If fso.FileExists("C:\test.txt") Then
Debug.Print "ファイルが存在します"
Else
Debug.Print "ファイルが存在しません"
End If
'オブジェクトを解放
Set fso = Nothing
End Sub
CreateObjectと参照設定の違い【遅延バインディング vs 早期バインディング】
比較表
| 項目 | CreateObject(遅延バインディング) | 参照設定(早期バインディング) |
|---|---|---|
| 宣言方法 | Dim fso As Object | Dim fso As FileSystemObject |
| オブジェクト生成 | Set fso = CreateObject(...) | Set fso = New FileSystemObject |
| 参照設定 | ❌ 不要 | ✅ 必要(ツール→参照設定) |
| インテリセンス | ❌ 効かない | ✅ 効く(自動候補表示) |
| 処理速度 | 遅い | 速い |
| 環境依存 | 低い | 高い(参照設定がずれるとエラー) |
| 配布のしやすさ | ✅ 容易 | ❌ 環境調整が必要 |
| コンパイルエラー | 実行時に判明 | コンパイル時に判明 |
悪い例: 参照設定(環境依存)
'参照設定が必要(ツール→参照設定→Microsoft Scripting Runtime)
Sub EarlyBindingExample()
'特定の型で宣言
Dim fso As FileSystemObject
Set fso = New FileSystemObject
'他のPCで参照設定がずれているとエラー
Debug.Print fso.GetFileName("C:\test.txt")
Set fso = Nothing
End Sub
問題点:
- 他のPCで参照設定がずれているとエラーになる
- Officeのバージョン違いで動かない可能性
良い例: CreateObject(環境非依存)
Sub LateBindingExample()
'Object型で宣言
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
'環境依存しない
Debug.Print fso.GetFileName("C:\test.txt")
Set fso = Nothing
End Sub
メリット:
- 参照設定が不要
- 環境依存しにくい
- 配布が容易
使い分けのベストプラクティス
開発時: 参照設定(早期バインディング)
- インテリセンスでコーディング効率UP
- 型チェックでバグを早期発見
配布時: CreateObject(遅延バインディング)
- 環境依存を回避
- 参照設定トラブルを防ぐ
推奨アプローチ:
'開発時は参照設定でコーディング
'→ 配布前にCreateObjectに書き換える
'または条件コンパイルで切り替える
CreateObjectの基本構文とエラー処理
基本テンプレート
Sub CreateObjectTemplate()
Dim obj As Object
On Error GoTo ErrorHandler
'オブジェクト作成
Set obj = CreateObject("プログラムID")
'処理
Debug.Print "オブジェクト作成成功"
'クリーンアップ
Set obj = Nothing
Exit Sub
ErrorHandler:
If Err.Number = 429 Then
MsgBox "オブジェクトを作成できません。" & vbCrLf & _
"必要なライブラリがインストールされているか確認してください。", _
vbCritical
Else
MsgBox "エラー: " & Err.Description, vbCritical
End If
End Sub
実例2: エラー処理付きCreateObject
Function CreateFSO() As Object
'FileSystemObjectを安全に作成
Dim fso As Object
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
If Err.Number <> 0 Then
Debug.Print "FSO作成失敗: " & Err.Description
Set fso = Nothing
End If
On Error GoTo 0
Set CreateFSO = fso
End Function
'使用例
Sub UseFSO()
Dim fso As Object
Set fso = CreateFSO()
If Not fso Is Nothing Then
Debug.Print "FSO使用可能"
'処理
Set fso = Nothing
Else
MsgBox "FileSystemObjectが利用できません", vbCritical
End If
End Sub
FileSystemObject完全解説【ファイル・フォルダ操作】
FileSystemObjectの主要メソッド
| メソッド | 説明 | 使用例 |
|---|---|---|
| FileExists | ファイルの存在確認 | fso.FileExists("C:\test.txt") |
| FolderExists | フォルダの存在確認 | fso.FolderExists("C:\Logs") |
| CreateFolder | フォルダ作成 | fso.CreateFolder("C:\NewFolder") |
| DeleteFile | ファイル削除 | fso.DeleteFile("C:\test.txt") |
| CopyFile | ファイルコピー | fso.CopyFile "C:\src.txt", "C:\dst.txt" |
| MoveFile | ファイル移動 | fso.MoveFile "C:\src.txt", "D:\dst.txt" |
| GetFileName | ファイル名取得 | fso.GetFileName("C:\test.txt") |
| GetBaseName | 拡張子なしファイル名 | fso.GetBaseName("test.txt") |
実例3: ファイルの存在確認と作成
Sub FileOperations()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim filePath As String
filePath = "C:\test.txt"
'ファイルの存在確認
If Not fso.FileExists(filePath) Then
Debug.Print "ファイルが存在しないので作成します"
'テキストファイル作成
Dim txtFile As Object
Set txtFile = fso.CreateTextFile(filePath, True)
txtFile.WriteLine "これはテストファイルです"
txtFile.WriteLine "作成日時: " & Now
txtFile.Close
Debug.Print "ファイル作成完了: " & filePath
Else
Debug.Print "ファイルは既に存在します"
End If
Set txtFile = Nothing
Set fso = Nothing
End Sub
実例4: フォルダ内のファイル一覧取得
Sub ListFilesInFolder()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim folderPath As String
folderPath = "C:\Logs"
'フォルダの存在確認
If Not fso.FolderExists(folderPath) Then
MsgBox "フォルダが存在しません: " & folderPath, vbExclamation
Exit Sub
End If
'フォルダオブジェクト取得
Dim folder As Object
Set folder = fso.GetFolder(folderPath)
'ファイル一覧を取得
Dim file As Object
Debug.Print "=== ファイル一覧 ==="
For Each file In folder.Files
Debug.Print "ファイル名: " & file.Name
Debug.Print "サイズ: " & file.Size & " bytes"
Debug.Print "更新日: " & file.DateLastModified
Debug.Print "---"
Next file
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
実例5: ファイルのコピーとバックアップ
Sub BackupFile()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
On Error GoTo ErrorHandler
Dim sourceFile As String
Dim backupFile As String
sourceFile = "C:\data.xlsx"
backupFile = "C:\Backup\data_" & Format(Now, "yyyymmdd_hhnnss") & ".xlsx"
'ソースファイルの存在確認
If Not fso.FileExists(sourceFile) Then
MsgBox "ソースファイルが見つかりません: " & sourceFile, vbCritical
Exit Sub
End If
'バックアップフォルダの作成(存在しない場合)
Dim backupFolder As String
backupFolder = fso.GetParentFolderName(backupFile)
If Not fso.FolderExists(backupFolder) Then
fso.CreateFolder backupFolder
Debug.Print "バックアップフォルダを作成: " & backupFolder
End If
'ファイルをコピー
fso.CopyFile sourceFile, backupFile
Debug.Print "バックアップ完了: " & backupFile
Set fso = Nothing
Exit Sub
ErrorHandler:
MsgBox "バックアップ失敗: " & Err.Description, vbCritical
Set fso = Nothing
End Sub
実例6: テキストファイルの読み書き
Sub ReadWriteTextFile()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim filePath As String
filePath = "C:\log.txt"
'========== 書き込み ==========
Dim txtWrite As Object
Set txtWrite = fso.CreateTextFile(filePath, True)
txtWrite.WriteLine "ログ開始: " & Now
txtWrite.WriteLine "処理1完了"
txtWrite.WriteLine "処理2完了"
txtWrite.WriteLine "ログ終了: " & Now
txtWrite.Close
Debug.Print "ファイル書き込み完了"
'========== 読み込み ==========
Dim txtRead As Object
Set txtRead = fso.OpenTextFile(filePath, 1) '1=読み取り
Debug.Print "=== ファイル内容 ==="
Do Until txtRead.AtEndOfStream
Debug.Print txtRead.ReadLine
Loop
txtRead.Close
Set txtRead = Nothing
Set txtWrite = Nothing
Set fso = Nothing
End Sub
Dictionary完全解説【連想配列の基本】
Dictionaryとは?
**Dictionary(辞書)**は、キーと値のペアでデータを管理する連想配列です。
配列との違い:
- 配列: インデックス(0, 1, 2…)でアクセス
- Dictionary: キー(“名前”, “価格”など)でアクセス
実例7: Dictionaryの基本操作
Sub DictionaryBasic()
'Dictionaryオブジェクト作成
Dim dic As Object
Set dic = CreateObject("Scripting.Dictionary")
'========== データ追加 ==========
dic.Add "商品A", 1000
dic.Add "商品B", 1500
dic.Add "商品C", 2000
'========== データ取得 ==========
Debug.Print "商品Aの価格: " & dic("商品A") '→ 1000
'========== キーの存在確認 ==========
If dic.Exists("商品B") Then
Debug.Print "商品Bは存在します"
End If
'========== データ変更 ==========
dic("商品A") = 1100
Debug.Print "商品Aの新価格: " & dic("商品A") '→ 1100
'========== データ削除 ==========
dic.Remove "商品C"
Debug.Print "商品C削除後の件数: " & dic.Count '→ 2
'========== 全削除 ==========
dic.RemoveAll
Debug.Print "全削除後の件数: " & dic.Count '→ 0
Set dic = Nothing
End Sub
実例8: Dictionaryでデータ集計
Sub CountProductSales()
Dim dic As Object
Set dic = CreateObject("Scripting.Dictionary")
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("売上データ")
'売上データを集計(A列:商品名、B列:数量)
Dim i As Long
For i = 2 To ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Dim productName As String
Dim quantity As Long
productName = ws.Cells(i, 1).Value
quantity = ws.Cells(i, 2).Value
'商品が既に存在すれば加算、なければ追加
If dic.Exists(productName) Then
dic(productName) = dic(productName) + quantity
Else
dic.Add productName, quantity
End If
Next i
'結果を出力
Debug.Print "=== 商品別売上数量 ==="
Dim key As Variant
For Each key In dic.Keys
Debug.Print key & ": " & dic(key) & "個"
Next key
Set dic = Nothing
Set ws = Nothing
End Sub
実例9: Dictionaryで重複チェック
Sub CheckDuplicates()
Dim dic As Object
Set dic = CreateObject("Scripting.Dictionary")
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("データ")
'A列のデータで重複チェック
Dim i As Long
Dim value As String
Dim duplicates As String
For i = 2 To ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
value = ws.Cells(i, 1).Value
If dic.Exists(value) Then
'重複発見
ws.Cells(i, 1).Interior.Color = RGB(255, 0, 0)
duplicates = duplicates & value & " (行" & i & "), "
Else
dic.Add value, i
End If
Next i
'結果表示
If duplicates <> "" Then
MsgBox "重複データ: " & vbCrLf & duplicates, vbExclamation
Else
MsgBox "重複データはありません", vbInformation
End If
Set dic = Nothing
Set ws = Nothing
End Sub
ADODB完全解説【データベース接続】
ADODBとは?
**ADODB(ActiveX Data Objects Database)**は、データベースに接続してSQL操作を行うためのライブラリです。
実例10: SQL Serverへの接続
Sub ConnectToSQLServer()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
On Error GoTo ErrorHandler
'接続文字列
Dim connStr As String
connStr = "Provider=SQLOLEDB;" & _
"Data Source=localhost;" & _
"Initial Catalog=SalesDB;" & _
"Integrated Security=SSPI;"
'データベース接続
conn.Open connStr
Debug.Print "データベース接続成功"
'SQLクエリ実行
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT * FROM Products", conn
'結果表示
Do Until rs.EOF
Debug.Print rs.Fields("ProductName").Value & ": " & rs.Fields("Price").Value
rs.MoveNext
Loop
'クリーンアップ
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
Exit Sub
ErrorHandler:
MsgBox "データベースエラー: " & Err.Description, vbCritical
If Not conn Is Nothing Then
If conn.State = 1 Then conn.Close
End If
Set conn = Nothing
End Sub
実例11: Accessデータベース操作
Sub QueryAccessDatabase()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
On Error GoTo ErrorHandler
'接続文字列(Access 2007以降)
Dim connStr As String
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Database\sales.accdb;"
conn.Open connStr
Debug.Print "Access接続成功"
'レコードセット取得
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT * FROM 顧客マスタ", conn
'Excelに出力
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("出力")
ws.Range("A1").CopyFromRecordset rs
Debug.Print "データ出力完了: " & rs.RecordCount & "件"
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
Set ws = Nothing
Exit Sub
ErrorHandler:
MsgBox "エラー: " & Err.Description, vbCritical
If Not conn Is Nothing Then
If conn.State = 1 Then conn.Close
End If
End Sub
Excel・Word・IEの外部操作
実例12: 別のExcelファイルを操作
Sub ControlAnotherExcel()
Dim xlApp As Object
Dim xlBook As Object
Set xlApp = CreateObject("Excel.Application")
On Error GoTo ErrorHandler
'別のExcelを開く
Set xlBook = xlApp.Workbooks.Open("C:\data.xlsx")
'データを取得
Dim value As Variant
value = xlBook.Worksheets("Sheet1").Range("A1").Value
Debug.Print "取得した値: " & value
'データを書き込み
xlBook.Worksheets("Sheet1").Range("B1").Value = "VBAから書き込み"
'保存して閉じる
xlBook.Save
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Exit Sub
ErrorHandler:
MsgBox "エラー: " & Err.Description, vbCritical
If Not xlApp Is Nothing Then xlApp.Quit
Set xlApp = Nothing
End Sub
実例13: Wordファイルを操作
Sub ControlWord()
Dim wdApp As Object
Dim wdDoc As Object
Set wdApp = CreateObject("Word.Application")
On Error GoTo ErrorHandler
'Wordを表示
wdApp.Visible = True
'新規ドキュメント作成
Set wdDoc = wdApp.Documents.Add
'文字を入力
wdDoc.Content.Text = "VBAからWordを操作しています" & vbCrLf & _
"作成日時: " & Now
'保存
wdDoc.SaveAs2 "C:\output.docx"
Debug.Print "Word文書作成完了"
'クリーンアップ
wdDoc.Close
wdApp.Quit
Set wdDoc = Nothing
Set wdApp = Nothing
Exit Sub
ErrorHandler:
MsgBox "エラー: " & Err.Description, vbCritical
If Not wdApp Is Nothing Then wdApp.Quit
End Sub
実例14: Internet Explorerを操作(Webスクレイピング)
Sub ControlIE()
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
On Error GoTo ErrorHandler
'IEを表示
ie.Visible = True
'Webページを開く
ie.Navigate "https://example.com"
'読み込み完了まで待機
Do While ie.Busy Or ie.ReadyState <> 4
DoEvents
Loop
'ページタイトル取得
Debug.Print "ページタイトル: " & ie.Document.Title
'特定要素を取得(例: h1タグ)
Dim h1 As Object
Set h1 = ie.Document.getElementsByTagName("h1")(0)
Debug.Print "見出し: " & h1.innerText
'2秒待機後に閉じる
Application.Wait Now + TimeValue("00:00:02")
ie.Quit
Set h1 = Nothing
Set ie = Nothing
Exit Sub
ErrorHandler:
MsgBox "エラー: " & Err.Description, vbCritical
If Not ie Is Nothing Then ie.Quit
End Sub
エラー429の原因と対処法
エラー429とは?
実行時エラー ‘429’: ActiveX コンポーネントはオブジェクトを作成できません。
主な原因
| 原因 | 説明 | 対処法 |
|---|---|---|
| プログラムIDの誤り | CreateObject("Scripting.Dictionary")のスペルミス | 正しいプログラムIDを確認 |
| ライブラリ未インストール | 必要なコンポーネントがインストールされていない | ライブラリをインストール |
| レジストリ破損 | COMオブジェクトの登録情報が破損 | レジストリを修復 |
| 権限不足 | 管理者権限が必要な場合 | 管理者として実行 |
| 32bit/64bit問題 | Office 64bit版で32bitコンポーネント使用 | 対応版を使用 |
実例15: エラー429の安全な処理
Sub SafeCreateObject()
Dim obj As Object
On Error Resume Next
'========== FSO作成を試行 ==========
Set obj = CreateObject("Scripting.FileSystemObject")
If Err.Number = 429 Then
MsgBox "FileSystemObjectを作成できません。" & vbCrLf & _
"以下を確認してください:" & vbCrLf & _
"1. Windows Scripting Runtimeがインストールされているか" & vbCrLf & _
"2. 管理者権限で実行しているか", _
vbCritical, "エラー429"
Exit Sub
ElseIf Err.Number <> 0 Then
MsgBox "予期しないエラー: " & Err.Description, vbCritical
Exit Sub
End If
On Error GoTo 0
'正常処理
Debug.Print "オブジェクト作成成功"
Set obj = Nothing
End Sub
エラー429の予防策
1. プログラムIDを定数で管理
Private Const PROGID_FSO As String = "Scripting.FileSystemObject"
Private Const PROGID_DIC As String = "Scripting.Dictionary"
Private Const PROGID_ADODB As String = "ADODB.Connection"
Sub UseConstants()
Dim fso As Object
Set fso = CreateObject(PROGID_FSO) 'スペルミス防止
Set fso = Nothing
End Sub
2. オブジェクト作成を関数化
Function CreateFSOSafe() As Object
Dim fso As Object
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
On Error GoTo 0
Set CreateFSOSafe = fso
End Function
Sub UseHelper()
Dim fso As Object
Set fso = CreateFSOSafe()
If fso Is Nothing Then
MsgBox "FSO作成失敗", vbCritical
Exit Sub
End If
'fsoを使った処理
Set fso = Nothing
End Sub
よくある質問(FAQ)7問
Q1. CreateObjectと参照設定はどちらを使うべき?
A. 基本はCreateObject(遅延バインディング)を推奨します。
理由:
- 環境依存しにくい
- 参照設定トラブルを回避
- 配布が容易
開発効率を優先する場合は参照設定を使い、配布前にCreateObjectに書き換えるのがベストです。
Q2. CreateObjectでインテリセンスを効かせる方法は?
A. 開発時だけ参照設定して、配布時に外すのが実用的です。
または、コメントでメソッド一覧を記載しておくと便利です。
'FileSystemObjectの主要メソッド
' FileExists, FolderExists, CreateFolder, DeleteFile
' CopyFile, MoveFile, CreateTextFile, OpenTextFile
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Q3. CreateObjectで作成したオブジェクトは必ずNothingにするべき?
A. 推奨です。明示的にSet obj = Nothingで解放してください。
Sub ProperCleanup()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
'処理
'必ずNothingで解放
Set fso = Nothing
End Sub
理由:
- メモリリークを防ぐ
- ファイルロックを解除
- 他のプロセスへの影響を避ける
Q4. CreateObjectが失敗する場合の確認方法は?
A. 以下の順で確認してください。
- プログラムIDのスペル確認
'正: "Scripting.FileSystemObject"
'誤: "Scripting.FilesystemObject"(sが小文字)
- レジストリ確認
Win + R → regedit →
HKEY_CLASSES_ROOT\Scripting.FileSystemObject
- 管理者権限で実行
- Office 32bit/64bitの確認
Q5. Excel.Applicationを複数起動できる?
A. はい、できます。
Sub MultipleExcel()
'Excel1を起動
Dim xlApp1 As Object
Set xlApp1 = CreateObject("Excel.Application")
xlApp1.Visible = True
xlApp1.Workbooks.Add
'Excel2を起動
Dim xlApp2 As Object
Set xlApp2 = CreateObject("Excel.Application")
xlApp2.Visible = True
xlApp2.Workbooks.Add
Debug.Print "Excelを2つ起動しました"
'個別に終了
xlApp1.Quit
xlApp2.Quit
Set xlApp1 = Nothing
Set xlApp2 = Nothing
End Sub
Q6. CreateObjectで作成したExcelが終了しない?
A. 必ず.Quitメソッドを呼んでください。
Sub ProperExcelQuit()
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
'処理
'必ずQuitを呼ぶ
xlApp.Quit
Set xlApp = Nothing
End Sub
タスクマネージャーでプロセスが残っている場合:
- VBEを閉じてExcelを再起動
- タスクマネージャーで手動終了
Q7. FileSystemObjectの代替方法は?
A. VBAの組み込み関数でも基本的なファイル操作は可能です。
| 操作 | FileSystemObject | VBA組み込み関数 |
|---|---|---|
| 存在確認 | fso.FileExists | Dir関数 |
| ファイル削除 | fso.DeleteFile | Kill文 |
| ファイル名取得 | fso.GetFileName | Dir関数 |
| フォルダ作成 | fso.CreateFolder | MkDir文 |
ただし、FileSystemObjectの方が機能が豊富で使いやすいため、積極的に活用することを推奨します。
まとめ
この記事で学んだこと
- CreateObjectの基本構文と使い方
- 参照設定との違い(遅延バインディング vs 早期バインディング)
- FileSystemObject・Dictionary・ADODBの実践的な使い方
- Excel・Word・IEの外部操作方法
- エラー429の原因と対処法

コメント