VBAからGDI+を使う資料集
inet上の達人の方々から御教示いただいたコードを少しアレンジさせてもらっています(切り貼りとも言います)。
  1. ホーム
  2. EMF
  3. AutoShapeをUserformに表示1


AutoShapeをUserformに表示。その際フォーム寸法を画像に合わせる

AutoShapeをUserformに表示するというお題。昔グラフを表示させようといろいろやった事を思い出す。
EMFのサイズ取得を会得した今なら、画像サイズぴったりにフォームサイズを調整することができる
だろうとやってみました。試行錯誤の苦肉の策も盛り込んでありますが...
なお、Paste Picture関数は、コード中に借用先を明示してあります。


' User-Defined Types for API Calls
'Declare a UDT to store a GUID for the IPicture OLE Interface
Private Type GUID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(0 To 7) As Byte
End Type
'Declare a UDT to store the bitmap information
Private Type uPicDesc
    Size As Long
    Type As Long
    hPic As Long
    hpal As Long
End Type
Private Type RECTL
        Left As Long
        Top As Long
        Right As Long
        Bottom As Long
End Type
Public Type SIZEL
    cx As Long
    cy As Long
End Type
Private Type ENHMETAHEADER
        iType As Long
        nSize As Long
        rclBounds As RECTL
        rclFrame As RECTL '0.01mm単位
        dSignature As Long
        nVersion As Long
        nBytes As Long
        nRecords As Long
        nHandles As Integer
        sReserved As Integer
        nDescription As Long
        offDescription As Long
        nPalEntries As Long
        szlDevice As SIZEL
        szlMillimeters As SIZEL
End Type

'''Windows API Function Declarations
'Does the clipboard contain a bitmap/metafile?
Private Declare Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Integer) As Long
'Open the clipboard to read
Private Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
'Get a pointer to the bitmap/metafile
Private Declare Function GetClipboardData Lib "user32" (ByVal wFormat As Integer) As Long
'Close the clipboard
Private Declare Function CloseClipboard Lib "user32" () As Long
'Convert the handle into an OLE IPicture interface.
Private Declare Function OleCreatePictureIndirect Lib "olepro32.dll" (PicDesc As uPicDesc, RefIID As GUID, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long
'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare Function CopyEnhMetaFile Lib "gdi32" Alias "CopyEnhMetaFileA" (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long
'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.
Private Declare Function CopyImage Lib "user32" (ByVal handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long
Private Declare Function DeleteEnhMetaFile Lib "gdi32" (ByVal hEmf As Long) As Long
Private Declare Function GetEnhMetaFileHeader Lib "gdi32" ( _
  ByVal hEmf As Long, _
  ByVal MetaHeaderSize As Long, _
  ByRef MetaHeader As ENHMETAHEADER) As Long

'The API format types we're interested in
Const CF_BITMAP = 2
Const CF_PALETTE = 9
Const CF_ENHMETAFILE = 14
Const IMAGE_BITMAP = 0
Const LR_COPYRETURNORG = &H4

'ワークシート上のAutoShape(s)、グラフオブジェクト等をユーザーフォームに
'貼り付ける。その際、ユーザーフォームの寸法をぴったりに調整する。
Sub test()
  Dim myPic As StdPicture
  Dim picSize As SIZEL
  
  Selection.Copy
  Set myPic = PastePicture(xlPicture)
  picSize = readEMFsize
  UserForm1.Show vbModeless
  Call resizeForm(UserForm1, picSize)
  Set UserForm1.Picture = myPic
End Sub

'試行錯誤でユーザーフォームの有効寸法をグラフィックのサイズに合わせる
Private Sub resizeForm(myForm As Object, picSize As SIZEL)
  myForm.Width = picSize.cx * 72 / 96
  myForm.Height = picSize.cy * 72 / 96
  Do
    myForm.Width = myForm.Width + 0.25
  Loop Until myForm.InsideWidth >= picSize.cx * 72 / 96
  Do
    myForm.Height = myForm.Height + 0.25
  Loop Until myForm.InsideHeight >= picSize.cy * 72 / 96
End Sub

'クリップボードのメタファイルの画像寸法を取得
Private Function readEMFsize(Optional hEmf As Long = 0) As SIZEL
'  Dim hEmf As Long '拡張メタファイルのハンドル
  Dim mh As ENHMETAHEADER '取得結果のメタファイルヘッダ
  Dim emfWidth As Long, emfHeight As Long
  
  If hEmf = 0 Then
    Selection.Copy
    If OpenClipboard(0) Then
      hEmf = GetClipboardData(CF_ENHMETAFILE)
      ' ハンドルを複製してから使用する
      hEmf = CopyEnhMetaFile(hEmf, vbNullString)
      CloseClipboard
    End If
    If hEmf = 0 Then
      MsgBox "emf取得に失敗"
      Exit Function ' 失敗
    End If
  End If
   'ヘッダの取得
  GetEnhMetaFileHeader hEmf, Len(mh), mh
  With mh
    readEMFsize.cx = .rclBounds.Right - .rclBounds.Left
    readEMFsize.cy = .rclBounds.Bottom - .rclBounds.Top
  End With
  DeleteEnhMetaFile hEmf
End Function

'***************************************************************************
'*
'* MODULE NAME:     Paste Picture
'* AUTHOR & DATE:   STEPHEN BULLEN, Office Automation Ltd
'*                  15 November 1998
'* CONTACT:         Stephen@oaltd.co.uk
'* WEB SITE:        http://www.oaltd.co.uk
'*
'***************************************************************************
Function PastePicture(Optional lXlPicType As Long = xlPicture) As IPicture
  'Some pointers
  Dim h As Long, hPicAvail As Long, hPtr As Long, hpal As Long, lPicType As Long, hCopy As Long
  
  'Convert the type of picture requested from the xl constant to the API constant
  lPicType = IIf(lXlPicType = xlBitmap, CF_BITMAP, CF_ENHMETAFILE)
  'Check if the clipboard contains the required format
  hPicAvail = IsClipboardFormatAvailable(lPicType)
  If hPicAvail <> 0 Then
      'Get access to the clipboard
      h = OpenClipboard(0&)
      If h > 0 Then
          'Get a handle to the image data
          hPtr = GetClipboardData(lPicType)
          'Create our own copy of the image on the clipboard, in the appropriate format.
          If lPicType = CF_BITMAP Then
              hCopy = CopyImage(hPtr, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG)
          Else
              hCopy = CopyEnhMetaFile(hPtr, vbNullString)
          End If
          'Release the clipboard to other programs
          h = CloseClipboard
          'If we got a handle to the image, convert it into a Picture object and return it
          If hPtr <> 0 Then Set PastePicture = CreatePicture(hCopy, 0, lPicType)
      End If
  End If
End Function

Private Function CreatePicture(ByVal hPic As Long, ByVal hpal As Long, ByVal lPicType) As IPicture
  ' IPicture requires a reference to "OLE Automation"
  Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As GUID, IPic As IPicture
  
  'OLE Picture types
  Const PICTYPE_BITMAP = 1
  Const PICTYPE_ENHMETAFILE = 4
  
  ' Create the Interface GUID (for the IPicture interface)
  With IID_IDispatch
      .Data1 = &H7BF80980
      .Data2 = &HBF32
      .Data3 = &H101A
      .Data4(0) = &H8B
      .Data4(1) = &HBB
      .Data4(2) = &H0
      .Data4(3) = &HAA
      .Data4(4) = &H0
      .Data4(5) = &H30
      .Data4(6) = &HC
      .Data4(7) = &HAB
  End With
  ' Fill uPicInfo with necessary parts.
  With uPicInfo
      .Size = Len(uPicInfo)                                                   ' Length of structure.
      .Type = IIf(lPicType = CF_BITMAP, PICTYPE_BITMAP, PICTYPE_ENHMETAFILE)  ' Type of Picture
      .hPic = hPic                                                            ' Handle to image.
      .hpal = IIf(lPicType = CF_BITMAP, hpal, 0)                              ' Handle to palette (if bitmap).
  End With
  ' Create the Picture object.
  r = OleCreatePictureIndirect(uPicInfo, IID_IDispatch, True, IPic)
  ' If an error occured, show the description
  If r <> 0 Then Debug.Print "Create Picture: " & fnOLEError(r)
  ' Return the new Picture object.
  Set CreatePicture = IPic
End Function

Private Function fnOLEError(lErrNum As Long) As String
  'OLECreatePictureIndirect return values
  Const E_ABORT = &H80004004
  Const E_ACCESSDENIED = &H80070005
  Const E_FAIL = &H80004005
  Const E_HANDLE = &H80070006
  Const E_INVALIDARG = &H80070057
  Const E_NOINTERFACE = &H80004002
  Const E_NOTIMPL = &H80004001
  Const E_OUTOFMEMORY = &H8007000E
  Const E_POINTER = &H80004003
  Const E_UNEXPECTED = &H8000FFFF
  Const S_OK = &H0
  
  Select Case lErrNum
  Case E_ABORT
      fnOLEError = " Aborted"
  Case E_ACCESSDENIED
      fnOLEError = " Access Denied"
  Case E_FAIL
      fnOLEError = " General Failure"
  Case E_HANDLE
      fnOLEError = " Bad/Missing Handle"
  Case E_INVALIDARG
      fnOLEError = " Invalid Argument"
  Case E_NOINTERFACE
      fnOLEError = " No Interface"
  Case E_NOTIMPL
      fnOLEError = " Not Implemented"
  Case E_OUTOFMEMORY
      fnOLEError = " Out of Memory"
  Case E_POINTER
      fnOLEError = " Invalid Pointer"
  Case E_UNEXPECTED
      fnOLEError = " Unknown Error"
  Case S_OK
      fnOLEError = " Success!"
  End Select
End Function