Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function EmptyClipboard Lib "user32" () As Long
Private Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hwnd As LongPtr) As LongPtr
Private Declare PtrSafe Function CloseClipboard Lib "user32" () As Long
#Else
Private Declare Function EmptyClipboard Lib "user32" () As Long
Private Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function CloseClipboard Lib "user32" () As Long
#End If
Private Type FUNC_OUT_RESULTS
SUCCESS As Boolean
SAVED_FILE_PATH_NAME As String
ERROR As String
End Type
Sub TEST()
Dim tRes As FUNC_OUT_RESULTS
Dim oleObj As OLEObject
tRes = SaveEmbeddedOleObjectToDisk _
(EmbeddedObject:=ActiveSheet.OLEObjects("Object 1"), FilePathName:="C:\test\WAV_1.wav")
With tRes
If .SUCCESS Then
MsgBox "OleObject successfully saved as : '" & .SAVED_FILE_PATH_NAME & " '", vbInformation
Else
MsgBox .ERROR, vbCritical
End If
End With
End Sub
Private Function SaveEmbeddedOleObjectToDisk( _
ByVal EmbeddedObject As OLEObject, _
ByVal FilePathName As String _
) _
As FUNC_OUT_RESULTS
Dim oFolder As Object
Dim sFolder As String
On Error GoTo errHandler
If Len(Dir$(FilePathName)) <> 0 Then Err.Raise 58
sFolder = Left$(FilePathName, InStrRev(FilePathName, "\") - 1)
If Len(Dir$(sFolder, vbDirectory)) = 0 Then
MkDir sFolder
End If
If EmbeddedObject.OLEType = xlOLEEmbed Then
EmbeddedObject.Copy
Set oFolder = CreateObject("Shell.Application").Namespace(sFolder & Chr(0))
oFolder.Self.InvokeVerb "Paste"
Name GetPastedFile(sFolder) As FilePathName
SaveEmbeddedOleObjectToDisk.SAVED_FILE_PATH_NAME = FilePathName
SaveEmbeddedOleObjectToDisk.SUCCESS = True
End If
Call CleanClipBoard
Exit Function
errHandler:
SaveEmbeddedOleObjectToDisk.ERROR = Err.Description
Call CleanClipBoard
End Function
Private Function GetPastedFile( _
ByVal Folder As String _
) _
As String
Dim sCurFile As String
Dim sNewestFile As String
Dim dCurDate As Date
Dim dNewestDate As Date
Folder = Folder & "\"
sCurFile = Dir$(Folder & "*.*", vbNormal)
Do While Len(sCurFile) > 0
dCurDate = FileDateTime(Folder & sCurFile)
If dCurDate > dNewestDate Then
dNewestDate = dCurDate
sNewestFile = Folder & sCurFile
End If
sCurFile = Dir$()
Loop
GetPastedFile = sNewestFile
End Function
Private Sub CleanClipBoard()
OpenClipboard 0
EmptyClipboard
CloseClipboard
End Sub