?
Solved

Run-time error '380': Invalid property value

Posted on 2014-08-29
6
Medium Priority
?
615 Views
Last Modified: 2014-09-04
I have obtained some code that will allow me to copy a range to the clipboard then save it as a BMP file.

A run-time error is occuring and I have no idea why...
SavePicture oPic, vFile

Here is the code that calls the MakePicFile sub
Public Sub subSaveSheetsAsBMPs()
    strWorkSheets = Array("Sheet1", "Sheet2")
    For Each strWorkSheet In strWorkSheets
        With Worksheets(strWorkSheet)
            .Select
            ' Set the range to be saved as a BMP
            intLastRow = .Cells(Rows.Count, "A").End(xlUp).Row
            Dim TargetRange As Range
            Set TargetRange = .Range(Cells(1, "A"), Cells(intLastRow, "W"))
            ' Save the BMP to file
            Call MakePicFile(strWorkSheet, TargetRange)
        End With
    Next strWorkSheet
End Sub

Open in new window


The other procedures and functions being called...
'* AUTHOR & DATE:   STEPHEN BULLEN, Office Automation Ltd
'*                  15 November 1998
'*
'* CONTACT:         Stephen@oaltd.co.uk
'* WEB SITE:        http://www.oaltd.co.uk
'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
    
    '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
    Private Declare Function EmptyClipboard 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
    
    'The API format types we're interested in
    Private Const CF_BITMAP = 2
    Private Const CF_PALETTE = 9
    Private Const CF_ENHMETAFILE = 14
    Private Const IMAGE_BITMAP = 0
    Private Const LR_COPYRETURNORG = &H4
    
    'OLE Picture types
    Private Const PICTYPE_BITMAP = 1
    Private Const PICTYPE_ENHMETAFILE = 4
'======================================================================================================

Public Function PastePicture(Optional lXlPicType As Long = xlPicture) As IPicture
    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
        h = OpenClipboard(0&)   'Get access to the clipboard
        If h > 0 Then
            hPtr = GetClipboardData(lPicType) 'Get a handle to the image data
            
            '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
            
           'clear then close clipboard
            EmptyClipboard

            h = CloseClipboard  'Release the clipboard to other programs
            
            '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
    Else
        MsgBox "Fault"
    End If
End Function

Private Function CreatePicture(ByVal hPic As Long, ByVal hPal As Long, ByVal lPicType) As IPicture
    Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As GUID, IPic As IPicture
    
    ' 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 Error"
    
    Set CreatePicture = IPic    ' Return the new Picture object.
End Function

Public Sub MakePicFile(strSheetName, TargetRange As Range)
blnScreenUpdating = Application.ScreenUpdating
Application.ScreenUpdating = True
Dim vFile As Variant
Dim oPic As IPictureDisp

'copy range to new tab(sheet)
'change destination range to suit
Sheets.Add.Name = strSheetName & "BMP"
TargetRange.Copy Destination:=Sheets(strSheetName & "BMP").Range("A1")
Application.CutCopyMode = False

'copy range to bmp file
TargetRange.Copy

'set the filepath and filename
strFilePathandName = ThisWorkBook.Path & strSheetName & ".bmp"

'delete the bmp if it already exists
Call DeleteFile(strFilePathandName)

'change file path to suit
vFile = strFilePathandName
Set oPic = PastePicture(CF_BITMAP)
SavePicture oPic, vFile
Application.CutCopyMode = False
Application.ScreenUpdating = blnScreenUpdating
End Sub

Open in new window

0
Comment
Question by:antonioking
  • 4
  • 2
6 Comments
 
LVL 50

Expert Comment

by:Martin Liss
ID: 40293036
You don't need the vFile variable so try changing line 141 to
SavePicture oPic, strFilePathandName
If you still what to use vFile then define it as a String.
0
 

Author Comment

by:antonioking
ID: 40296263
Thanks, I've made the change you suggested but the error is still occurring.
0
 
LVL 50

Expert Comment

by:Martin Liss
ID: 40296872
I believe in using Option Explicit in all my code so in order for me to run the code I had to define some variables. I also changed the path for the BMP files (see line 138) and deleted line 141 because you didn't supply that sub but in any case it's not needed. After doing those things it ran without errors. Two things I noticed however are that it only makes a picture out of row 1 of each sheet and it leaves behind two new sheets called Sheet1BMP and Sheet2BMP.

Give the code below a try (make sure like 138 will work for you  and let me know what happens.

Option Explicit

'* AUTHOR & DATE:   STEPHEN BULLEN, Office Automation Ltd
'*                  15 November 1998
'*
'* CONTACT:         Stephen@oaltd.co.uk
'* WEB SITE:        http://www.oaltd.co.uk
'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
    
    '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
    Private Declare Function EmptyClipboard 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
    
    'The API format types we're interested in
    Private Const CF_BITMAP = 2
    Private Const CF_PALETTE = 9
    Private Const CF_ENHMETAFILE = 14
    Private Const IMAGE_BITMAP = 0
    Private Const LR_COPYRETURNORG = &H4
    
    'OLE Picture types
    Private Const PICTYPE_BITMAP = 1
    Private Const PICTYPE_ENHMETAFILE = 4
'======================================================================================================

Public Function PastePicture(Optional lXlPicType As Long = xlPicture) As IPicture
    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
        h = OpenClipboard(0&)   'Get access to the clipboard
        If h > 0 Then
            hPtr = GetClipboardData(lPicType) 'Get a handle to the image data
            
            '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
            
           'clear then close clipboard
            EmptyClipboard

            h = CloseClipboard  'Release the clipboard to other programs
            
            '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
    Else
        MsgBox "Fault"
    End If
End Function

Private Function CreatePicture(ByVal hPic As Long, ByVal hPal As Long, ByVal lPicType) As IPicture
    Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As GUID, IPic As IPicture
    
    ' 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 Error"
    
    Set CreatePicture = IPic    ' Return the new Picture object.
End Function

Public Sub MakePicFile(strSheetName, TargetRange As Range)
Dim strFilePathandName As String
Dim blnScreenUpdating As Boolean

blnScreenUpdating = Application.ScreenUpdating
Application.ScreenUpdating = True
Dim vFile As Variant
Dim oPic As IPictureDisp

'copy range to new tab(sheet)
'change destination range to suit
Sheets.Add.Name = strSheetName & "BMP"
TargetRange.Copy Destination:=Sheets(strSheetName & "BMP").Range("A1")
Application.CutCopyMode = False

'copy range to bmp file
TargetRange.Copy

'set the filepath and filename
strFilePathandName = "C:\temp\" & strSheetName & ".bmp" ' ThisWorkbook.Path & strSheetName & ".bmp"

'delete the bmp if it already exists
'Call DeleteFile(strFilePathandName)

'change file path to suit
vFile = strFilePathandName
Set oPic = PastePicture(CF_BITMAP)
SavePicture oPic, vFile
Application.CutCopyMode = False
Application.ScreenUpdating = blnScreenUpdating
End Sub
Public Sub subSaveSheetsAsBMPs()
    Dim varWorksheets() As Variant
    Dim varWorksheet As Variant
    Dim lngLastRow As Long
    varWorksheets = Array("Sheet1", "Sheet2")
    For Each varWorksheet In varWorksheets
        With Worksheets(varWorksheet)
            .Select
            ' Set the range to be saved as a BMP
            lngLastRow = .Cells(Rows.Count, "A").End(xlUp).Row
            Dim TargetRange As Range
            Set TargetRange = .Range(Cells(1, "A"), Cells(lngLastRow, "W"))
            ' Save the BMP to file
            Call MakePicFile(varWorksheet, TargetRange)
        End With
    Next varWorksheet
End Sub

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 50

Accepted Solution

by:
Martin Liss earned 2000 total points
ID: 40296940
The original code only copied what was in columns A to W. Here's code that copies all the data on each sheet and does it without creating the Sheet1BMP and Sheet2BMP sheets.

Option Explicit

'* AUTHOR & DATE:   STEPHEN BULLEN, Office Automation Ltd
'*                  15 November 1998
'*
'* CONTACT:         Stephen@oaltd.co.uk
'* WEB SITE:        http://www.oaltd.co.uk
'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
    
    '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
    Private Declare Function EmptyClipboard 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
    
    'The API format types we're interested in
    Private Const CF_BITMAP = 2
    Private Const CF_PALETTE = 9
    Private Const CF_ENHMETAFILE = 14
    Private Const IMAGE_BITMAP = 0
    Private Const LR_COPYRETURNORG = &H4
    
    'OLE Picture types
    Private Const PICTYPE_BITMAP = 1
    Private Const PICTYPE_ENHMETAFILE = 4
'======================================================================================================

Public Function PastePicture(Optional lXlPicType As Long = xlPicture) As IPicture
    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
        h = OpenClipboard(0&)   'Get access to the clipboard
        If h > 0 Then
            hPtr = GetClipboardData(lPicType) 'Get a handle to the image data
            
            '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
            
           'clear then close clipboard
            EmptyClipboard

            h = CloseClipboard  'Release the clipboard to other programs
            
            '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
    Else
        MsgBox "Fault"
    End If
End Function

Private Function CreatePicture(ByVal hPic As Long, ByVal hPal As Long, ByVal lPicType) As IPicture
    Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As GUID, IPic As IPicture
    
    ' 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 Error"
    
    Set CreatePicture = IPic    ' Return the new Picture object.
End Function

Public Sub MakePicFile(strSheetName, TargetRange As Range)
Dim strFilePathandName As String
Dim blnScreenUpdating As Boolean

blnScreenUpdating = Application.ScreenUpdating
Application.ScreenUpdating = True
Dim vFile As Variant
Dim oPic As IPictureDisp

'copy range to new tab(sheet)
'change destination range to suit
'new
'Sheets.Add.Name = strSheetName & "BMP"
'TargetRange.Copy Destination:=Sheets(strSheetName & "BMP").Range("A1")
TargetRange.Copy Destination:=Sheets(strSheetName).Range("A1")


Application.CutCopyMode = False

'copy range to bmp file
TargetRange.Copy

'set the filepath and filename
strFilePathandName = "C:\temp\" & strSheetName & ".bmp" ' ThisWorkbook.Path & strSheetName & ".bmp"

'delete the bmp if it already exists
'Call DeleteFile(strFilePathandName)

'change file path to suit
vFile = strFilePathandName
Set oPic = PastePicture(CF_BITMAP)
SavePicture oPic, vFile
Application.CutCopyMode = False
Application.ScreenUpdating = blnScreenUpdating
End Sub
Public Sub subSaveSheetsAsBMPs()
    Dim varWorksheets() As Variant
    Dim varWorksheet As Variant
    Dim lngLastRow As Long
    varWorksheets = Array("Sheet1", "Sheet2")
    For Each varWorksheet In varWorksheets
        With Worksheets(varWorksheet)
            .Select
            Call MakePicFile(varWorksheet, .UsedRange)
        End With
    Next varWorksheet
End Sub

Open in new window

0
 

Author Closing Comment

by:antonioking
ID: 40303442
Thanks this is even better, however the Run-time error is still occuring at line 150 SavePicture oPic, vFile
In particular if I hover over "oPic" in the debugger it reads the variable is nothing
Making me think the fault is actually with line 149 Set oPic = PastePicture(CF_BITMAP)

Maybe nothing is being copied?
0
 
LVL 50

Expert Comment

by:Martin Liss
ID: 40304013
It worked perfectly for me when I posted it but I ran into your same problem just now. It's probably a timing issue because  if you add a DoEvents line like the following it works again for me at least.
'change file path to suit
vFile = strFilePathandName
Set oPic = PastePicture(CF_BITMAP)
DoEvents
SavePicture oPic, vFile
Application.CutCopyMode = False
Application.ScreenUpdating = blnScreenUpdating

Open in new window

That indicates that in some cases the "PastePicture" process is taking too long and it doesn't finish before "SavePicture" happens. The fact that if without adding the DoEvents line you put a breakpoint on the "SavePicture" line it works too backs up my theory that it's a timing issue.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This code takes an Excel list of URL’s and adds a header titled “URL List”. It then searches through all URL’s in column “A”, looking for duplicates. When a duplicate is found, it is moved to the top of the list. The duplicate URL’s are then highlig…
Windows Explorer let you handle zip folders nearly as any other folder: Copy, move, change, and delete, etc. In VBA you can also handle normal files and folders, but zip folders takes a little more - and that you'll find here.
Graphs within dashboards are meant to be dynamic, representing data from a period of time that will change each time the dashboard is updated with new data. Rather than update each graph to point to a different set within a static set of data, t…
This Micro Tutorial demonstrates how to create Excel charts: column, area, line, bar, and scatter charts. Formatting tips are provided as well.

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question