HOME > 即効テクニック > AccessVBA > Windows環境・オブジェクト > クリップボードのデータを取り出す方法

即効テクニック

Windows環境・オブジェクト

クリップボードのデータを取り出す方法

(Access 97)
●概要●
Accessにはクリップボードのデータを取得する方法が用意されていません。
ここでは、VBAを使用してクリップボードからデータを取り出す方法を説明します。

●準備●
  1. 新規標準モジュールを用意し、以下のプロシージャを記述します。
  2. VBEのメニューから、[表示]−[イミディエイトウィンドウ](Ctrl+G)を選択し、イミディエイトウィンドウを表示させておきます。 ※ Access97の場合はデバッグウィンドウになりますので、以後読み替えて下さい。
●サンプルコード● 'Win32API宣言部 Declare Function OpenClipboard Lib "User32" (ByVal hwnd As Long _ ) As Long Declare Function CloseClipboard Lib "User32" () As Long Declare Function GetClipBoardData Lib "User32" _ Alias "GetClipboardData" _ (ByVal wFormat As Long _ ) As Long Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags&, _ ByVal dwBytes As Long _ ) As Long Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long _ ) As Long Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long _ ) As Long Declare Function GlobalSize Lib "kernel32" (ByVal hMem As Long _ ) As Long Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, _ ByVal lpString2 As Any _ ) As Long 'パブリック定数 Public Const GHND = &H42 Public Const CF_TEXT = 1 Public Const MAXSIZE = 4096 Function GetClipBoard() Dim hClipMemory As Long Dim lpClipMemory As Long Dim MyString As String Dim RetVal As Long 'クリップボードの状態チェック If OpenClipboard(0&) = 0 Then MsgBox "クリップボードを開けませんでした" Exit Function End If ' テキストを参照しているハンドルをグローバルメモリに取得 hClipMemory = GetClipboardData(CF_TEXT) If IsNull(hClipMemory) Then MsgBox "メモリが割り当てられません" GoTo OutOfHere End If ' メモリをロックして、実際のデータ文字列を参照できるようにする lpClipMemory = GlobalLock(hClipMemory) If Not IsNull(lpClipMemory) Then MyString = Space$(MAXSIZE) RetVal = lstrcpy(MyString, lpClipMemory) RetVal = GlobalUnlock(hClipMemory) '終端Null文字を取り除く MyString = Mid(MyString, 1, InStr(1, MyString, Chr$(0), 0) - 1) Else MsgBox "メモリの確保に失敗しました" End If OutOfHere: RetVal = CloseClipboard() GetClipBoard = MyString End Function ●動作確認● あらかじめ、Ctrl+C等で文字列をコピーしてから、イミディエイトウィンドウに以下のように入力して、Enter キーを押します。 ---------------------------------------- ? GetClipBoard() ---------------------------------------- ※「?」=Debug.Print すると、イミディエイトウィンドウにコピーしていたデータが表示され、クリップボードからデータを取り出せていることを確認できます。