- OLEとは
- Object Linking and Embedding
- アプリケーションから別のアプリケーションを操作したりできる
- 例:Wordに埋め込まれたExcelの表
OLEオートメーションの使い方
- 利用したいオブジェクトをあらかじめ参照設定する方法
- VBEでツール -> 参照設定 をクリックして、チェックボックスにチェックを入れる
Dim IE As New InternetExplorer
IE.Visible = True
IE.Navigate "http://vbae.odyssey-com.co.jp"
MsgBox "ページを表示しました"
IE.Quit
Set IE = Nothing
- 事前に参照設定せずに、VBAのコードでオブジェクトへの参照を行う
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "http://vbae.odyssey-com.co.jp/"
MsgBox "ページを表示しました"
IE.Quit
Set IE = Nothing
どちらがいいのか?
- 事前バインディングでは参照するオブジェクトをあらかじめ指定するため、プロパティやメソッドの自動メンバ表示が可能になる
- 実行時バインディングはCreateObject関数で好きなタイミングで参照できる
OLEオートメーションの注意
- Excelから他のアプリケーションを操作するのは容易ではない
- また、それぞれのアプリケーションのメソッド名等も自分で調べる必要がある
事例1:IntenetExplorerを操作する
- 変数名 = 値:一般的な例
- Set 変数名 = オブジェクト
- 例:Set IE = CreateObject("InternetExplorer.Application")
- Set 変数名 = Nothing
Option Explicit
Sub Macro1()
'
' Webページの内容をMsgBoxで表示する
'
Dim IE As Object, buf As String
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
'IE.Navigate "http://vbae.odyssey-com.co.jp/"
IE.Navigate "http://www.yahoo.co.jp/"
'IEの処理待ち
Do While IE.Busy = True
DoEvents
Loop
'IEの読み込み待ち
Do While IE.Document.ReadyState <> "complete"
DoEvents
Loop
buf = IE.Document.Body.InnerText
IE.Quit
MsgBox buf
Set IE = Nothing
'
End Sub
事例2:Windows Script Hostを利用する
- VBAでは難しいことをWSHでで実現する
- 例:5秒後に自動で閉じるポップアップ
Sub Macro1()
'
' WSHを利用する
'
Dim WSH As Object
Set WSH = CreateObject("WScript.Shell")
WSH.popup "5秒後に閉じます", 5, "テスト", vbInformation
Set WSH = Nothing
'
End Sub
11-2 APIとは
- APIは公開されている機能や関数だけを呼び出して実行する
- OLEはプログラムそのものを操作する
Option Explicit
Declare Function GetTickCount Lib "kernel32" () As Long
Sub Macro1()
'
' セルA1に1から1000までの数値を入力し、その時間を計測する
'GetTickCountはWindowsが起動してから現在までの時間をミリ秒単位で返す関数
Dim i As Long, start As Long
start = GetTickCount
For i = 1 To 10000
Range("A1").Value = i
Next i
MsgBox (GetTickCount - start) / 1000 & "秒"
'
End Sub
事例1:ゴミ箱に送る
Option Explicit
Declare Function SHFileOperation Lib "shell32.dll" _
(lpFileOp As SHFILEOPSTRUCT) As Long
'SHFileOperation関数に渡すユーザー定義型
Type SHFILEOPSTRUCT
hwnd As Long
wFunc As Long
pFrom As String
pTo As String
fFlags As Integer
fAnyOperationsAborted As Long
hNameMappings As Long
lpszProgressTitle As String
End Type
Sub Macro1()
'
' ファイル C:\sample.log をごみ箱に送る
'
Dim SH As SHFILEOPSTRUCT, re As Long
With SH
.hwnd = Application.hwnd
.wFunc = &H3
.pFrom = "C:\sample.log"
.fFlags = &H40
End With
re = SHFileOperation(SH)
'
End Sub