Run-time error '380': Invalid property value

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

antoniokingAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Martin LissOlder than dirtCommented:
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
antoniokingAuthor Commented:
Thanks, I've made the change you suggested but the error is still occurring.
0
Martin LissOlder than dirtCommented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Martin LissOlder than dirtCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
antoniokingAuthor Commented:
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
Martin LissOlder than dirtCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
VB Script

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.