Sub CopyShapesAsJednokrilno()
Dim wsSource As Worksheet
Dim wsTarget As Worksheet
Dim shpRam As shape
Dim shpKrilo As shape
Dim cell As Range
Dim rngPrintArea As Range
Dim pasteRange As Range
Dim aspectRatio As Double
Dim picName As String
Dim shapeInCell As Boolean
Dim picObject As Picture
Dim pic As shape
Dim shp As shape
Dim shpGroup As shape
On Error GoTo ErrorHandler
' Set the source and target worksheets
Set wsSource = ThisWorkbook.Sheets("crtez")
Set wsTarget = ThisWorkbook.Sheets("crtezi")
' Set the shapes
Set shpRam = wsSource.shapes("grpRam")
Set shpKrilo = wsSource.shapes("grpKrilo")
' Group the shapes
Set shpGroup = wsSource.shapes.Range(Array(shpRam.name, shpKrilo.name)).Group
' Define the print area on the target worksheet
Set rngPrintArea = wsTarget.Range(wsTarget.PageSetup.PrintArea)
' Find the first empty cell in the print area with no shapes in it
For Each cell In rngPrintArea
shapeInCell = False
For Each shp In wsTarget.shapes
If Not Intersect(cell, Range(shp.TopLeftCell, shp.BottomRightCell)) Is Nothing Then
shapeInCell = True
Exit For
End If
Next shp
If IsEmpty(cell) And Not shapeInCell Then
Set pasteRange = cell
Exit For
End If
Next cell
' If a suitable cell is found, copy and paste the grouped shapes as a picture
If Not pasteRange Is Nothing Then
' Copy the group shape as a picture
shpGroup.Copy
Set picObject = wsTarget.Pictures.Paste
Set pic = wsTarget.shapes(picObject.name)
' Get the name for the picture from the cell above the target cell
picName = pasteRange.Offset(-1, 0).value
' Set the name of the picture
pic.name = picName
' Set the top-left corner of the image to the top-left corner of the target cell
With pic
.top = pasteRange.top
.left = pasteRange.left
' Maintain the original aspect ratio
aspectRatio = .width / .height
' Resize the image to fit within the cell while maintaining the aspect ratio
If pasteRange.width / pasteRange.height > aspectRatio Then
.height = pasteRange.height
.width = .height * aspectRatio
Else
.width = pasteRange.width
.height = .width / aspectRatio
End If
.Placement = xlMoveAndSize
End With
Else
MsgBox "No suitable cell found in the print area.", vbExclamation
End If
' Ungroup the shapes after copying
shpGroup.Ungroup
Exit Sub
ErrorHandler:
MsgBox "An error occurred: " & Err.Description, vbExclamation
Exit Sub
End Sub