If you add a selection and save path to the book to Ryan Bradley's code, which will be more elastic:
Sub ExportImage() Dim sheet, zoom_coef, area, chartobj Dim sFilePath As String Dim sView As String 'Captures current window view sView = ActiveWindow.View 'Sets the current view to normal so there are no "Page X" overlays on the image ActiveWindow.View = xlNormalView 'Temporarily disable screen updating Application.ScreenUpdating = False Set sheet = ActiveSheet 'Set the file path to export the image to the user desktop 'I have to give credit to Kyle for this solution, found it here: 'http://stackoverflow.com/questions/17551238/vba-how-to-save-excel-workbook-to-desktop-regardless-of-user 'sFilePath = CreateObject("WScript.Shell").specialfolders("Desktop") & "\" & ActiveSheet.Name & ".png" '################## 'Łukasz : Save to workbook directory 'Asking for filename insted of ActiveSheet.Name is also good idea, without file extension dim FileID as string FileID=inputbox("Type a file name","Filename...?",ActiveSheet.Name) sFilePath = ThisWorkbook.Path & "\" & FileID & ".png" 'Łukasz:Change code to use Selection 'Simply select what you want to export and run the macro 'ActiveCell should be: Top Left 'it means select from top left corner to right bottom corner Dim r As Long, c As Integer, ar As Long, ac As Integer r = Selection.rows.Count c = Selection.Columns.Count ar = ActiveCell.Row ac = ActiveCell.Column ActiveSheet.PageSetup.PrintArea = Range(Cells(ar, ac), Cells(ar, ac)).Resize(r, c).Address 'Export print area as correctly scaled PNG image, courtasy of Winand 'Łukasz: zoom_coef can be constant = 0 to 5 can work too, but save is 0 to 4 zoom_coef = 5 '100 / sheet.Parent.Windows(1).Zoom '############# Set area = sheet.Range(sheet.PageSetup.PrintArea) area.CopyPicture xlPrinter 'xlBitmap ' Set chartobj = sheet.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef) chartobj.Chart.Paste chartobj.Chart.Export sFilePath, "png" chartobj.Delete 'Returns to the previous view ActiveWindow.View = sView 'Re-enables screen updating Application.ScreenUpdating = True 'Tells the user where the image was saved MsgBox ("Export completed! The file can be found here: :" & Chr(10) & Chr(10) & sFilePath) 'Close End Sub
Łukasz Małarzewski
source share