Take Screenshot in Excel VBA and save in a separate file - vba

I' trying to automate the generation of small-sized screenshots directly from excel sheet by clicking a button with VBA code in the background. Here is the situation:
I have to take screenshot of cellrange G1:I12, and save it in a filename
called scrt.png. The size of the screenshot should remain exactly the same as that of cellrange G1:I12
From one of the earlier posts, I found this code which seems to work by first including the screenshot of the mentioned range to a new ChartSheet, and then it saves the scrt.png file at the mentioned location successfully. In essence, it successfully generates a bitmap of the selected cell range in the ChartSheet, and also generates the seperate scrt.png file at the mentioned location.
However, the problem with the code is that the scrt.png file that is created is having the whole ChartSheet screenshot. What I am looking for only the file saved with mentioned cell range snap.
Have tried to tweak the code, but no success. Any help will be greatly appreciated.
Sub Macro1()
myFileName = "scrt.png"
Range("G1:I12").Select
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
Charts.Add
ActiveChart.Paste
ActiveChart.Export Filename:=ThisWorkbook.Path & "\" & myFileName, Filtername:="PNG"
End Sub
Thanks a lot.

Instead of using a Chart sheet, use an embedded chartObject on a regular worksheet - then you can resize it before pasting in the copied range picture
Sub Tester()
ExportRange Selection, "C:\_Stuff\test\scrt.png"
End Sub
Sub ExportRange(rng As Range, sPath As String)
Dim cob, sc
rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture
Set cob = rng.Parent.ChartObjects.Add(10, 10, 200, 200)
'remove any series which may have been auto-added...
Set sc = cob.Chart.SeriesCollection
Do While sc.Count > 0
sc(1).Delete
Loop
With cob
.Height = rng.Height
.Width = rng.Width
.Chart.Paste
.Chart.Export Filename:=sPath, Filtername:="PNG"
.Delete
End With
End Sub

Related

VBA macro failing after windows 10 switch

I am working with a large macro, part of the code copies some cells to a chart object in order to save it as a .png and attach it to an email. After switching to windows 10, the chart object is empty. Oddly enough, if you add a breakpoint above the paste action, then resume the macro, everything works. This has me stumped. I've checked that the clipboard holds the table, and tried interrupting the code to replicate the breakpoint, nothing seems to work.
Edit:
this is the code that fails
Public Sub SaveTableRangeAs(ows As Worksheet, sFolderPath As String, sExtension As String, sRangeName As String)
Dim rng As Range
Dim cht
Set rng = ows.Range(sRangeName)
rng.CopyPicture xlScreen, xlPicture
Set cht = ows.ChartObjects.Add(0, 0, rng.Width, rng.Height)
'adding a breakpoint to line just below this one will result in the function working
With cht
.chart.Paste
.chart.Export sFolderPath & sRangeName & "." & sExtension
.Delete
End With
End Sub

Excel VBA export and append to PDF

I am looking for some help to solve a save to PDF problem. I have a sheet with some information that prints on 2 pages. The information displayed on this sheet is controlled by a drop down option to select 1 of several hundred options. I have a print to PDF function working fine for a single view of the information displayed so I select 1 option using the drop down and click the save to PDF button which all works great.
I need to add a 2nd function that will loop through all of the options available in the drop down box and add all of this into a single PDF to be saved. I can handle all of the standard code in the loop but how do I build up the PDF file inside the loop. I know how to build an array of sheets to export to a single PDF but this kind of 'in loop' function is something I am struggling to find an answer to.
Can anyone help please? If you need any more info, please just ask.
Thanks
In the Solution, suppose that we have a table which named: Table2.
We have also a help sheet(to store filtered tables) which is Hiden and named: Help.
Option Explicit
Sub print_to_pdf()
Dim sh As Long
Dim rg As Range
Dim Rng As Range
Dim rw As Range
Application.ScreenUpdating = False
For Each rw In Range("Table2[#All]").Rows
If rw.EntireRow.Hidden = False Then
If Rng Is Nothing Then Set Rng = rw
Set Rng = Union(rw, Rng)
End If
Next
Rng.Copy
With Sheets("help")
.Visible = True
sh = .Cells(Rows.Count, "A").End(xlUp).Row + 2
Set rg = Range("a3" & ":" & "a" & sh - 2)
.Activate
.Cells(sh, "A").Select
ActiveSheet.Paste
ActiveSheet.PageSetup.PrintArea = rg
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\rep.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
.Visible = False
End With
Application.ScreenUpdating = True
MsgBox "Your PDF Has been Created with Success!!", vbInformation
End Sub
You can append data in Help sheet then export pdf.
Ref: https://stackoverflow.com/questions/

Converting multiple sheet Excel file to PDF using VBA error

I am currently trying to convert a multiple sheet excel file to a PDF using VBA using the following code:
Private Sub CommandButton1_Click()
Dim mySheets As Variant, sh
mySheets = Array("Sheet1", "Sheet2", "Sheet3")
For Each sh In mySheets
Sheets(sh).PageSetup.Orientation = xlLandscape
Next
Sheets(mySheets).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="S:\GasInc\Services\B&ITS\OpsEng\EngServ\_Station Design\Projects\Station Co-ops\Angela Lian" & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False
End Sub
It converts my file fine, however for what I have on sheet 2 it splits it up into multiple pages in the PDF because I guess it does not scale it to fit the page. I was wondering how I could modify the code to make it scale this sheet so it will fit on one page of the PDF.
Thanks!
I have a similar sub in one of the tools I use. Do you have your worksheet's width / height scale to fit properties set to 1 page?
For Each sh In mySheets
With Sheets(sh).PageSetup
.Orientation = xlLandscape
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Next sh
One of the weird things I've run into is scaling issues when converting to PDF with some chart / image objects. For instance a logo looks fine on screen but prints stretched on the pdf. I never fixed the problem, but through research it seemed due to the way the printer sees it compared to the screen resolution. Have you ever run into that problem?

Excel VBA Export chart

I know absolutely nothing about VBA, I'm just trying to have 4 charts (that are already separated in their own tabs) be seamlessly exported as PNG files to a prespecified location every time I save an excel document.
Going through some of stackoverflow's database I managed to do something similar with a worksheet that I wanted to export as a CSV, but I can't manage to do the same for my charts.
Right now thats what my VBA looks like for ThisWorkbook:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.DisplayAlerts = False
Application.ScreenUpdating = False
ThisWorkbook.Worksheets("CSV Monthly Update").Copy
ActiveWorkbook.SaveAs Filename:="CSV Monthly Update.csv", FileFormat:=xlCSVWindows
ActiveWorkbook.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
'This above part works well'
'The one below doesn't, I'm trying to get the chart from Worksheet "Growth_of_10k" to be exported but it gives me a Runtime error 9 about runscript being out of page'
Sub ExportChart()
Dim objChrt As ChartObject
Dim myChart As Chart
Set objChrt = Sheets("Growth_of_10k").ChartObjects(3)
Set myChart = objChrt.Chart
myFileName = "myChart.png"
On Error Resume Next
Kill ThisWorkbook.Path & "\" & myFileName
On Error GoTo 0
myChart.Export Filename:=ThisWorkbook.Path & "\" & myFileName, Filtername:="PNG"
MsgBox "OK"
End Sub
Any idea how I would need to change the code so that the chart is exported automatically to the same location as the file (or another pre-specified location, it doesn't matter) at the same time as I save the excel document?
I'm sorry if this is a newbie question, this is really my very first endeavor with VBA and googling can only get you so far when you don't understand what you're doing.
Thanks a ton in advance.
A chart sheet is different from a chartobject embedded on a worksheet.
Thisworkbook.Sheets("Chart1").Export _
Filename:=ThisWorkbook.Path & "\" & myFileName, Filtername:="PNG"

Copying Excel source theme (formatting only) in VBA

I'm trying to programmatically copy a large range of cells from one workbook to another in VBA. I want to copy the formatting (including the entire source theme) and values, but NOT formulas. The following is my VBA code:
fromCells.Copy
toCells.PasteSpecial Paste:=xlPasteFormats
toCells.PasteSpecial Paste:=xlPasteColumnWidths
toCells.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Application.CutCopyMode = False
Unfortunately, there are occasions when the above code doesn't work. This is usually with Font face and size. I noticed that whenever this happens, the only way to copy the font formatting across is to use xlPasteAllUsingSourceTheme, so it seems the font formatting is somehow registered to a 'source theme'. Unfortunately, xlPasteAllUsingSourceTheme doesn't work for me because it's copying formulas as well.
So is there a way to copy the source theme (formatting only) across? Or maybe a way to force copy all the font formatting across?
Note: Copying using xlPasteAllUsingSourceTheme and then overwriting it with xlPasteValues won't work for me because when the formulas is copied it keeps popping up message boxes telling me about issues with the formulas (such as conflicting named ranges used in the formulas, etc.).
I'm using Excel 2013. I noticed this problem doesn't seem to arise in Excel 2007 or earlier. Any help is appreciated.
Edit: I've also tried the following code (added to the beginning of the above code), it still doesn't work...
Dim themeTempFilePath As String
themeTempFilePath = Environ("temp") & "\" & fromWorkbook.Name & "Theme.xml"
fromWorkbook.Theme.ThemeFontScheme.Save themeTempFilePath
toWorkbook.Theme.ThemeFontScheme.Load themeTempFilePath
fromWorkbook.Theme.ThemeColorScheme.Save themeTempFilePath
toWorkbook.Theme.ThemeColorScheme.Load themeTempFilePath
Update: It seems the above code for saving and loading themes does work. The problematic text that I was looking at came from a different place - a form control. It was copied as a picture (using Shape.CopyPicture) but somehow the font gets changed in the process. However, I'll post this issue as another question.
For this question, I'll put up the theme saving and loading mechanism as an answer.
Try 1 or 2
Option Explicit
Public Sub copyWithoutFormulas_1()
xlEnabled False
With Sheet2
.EnableCalculation = False
.EnableFormatConditionsCalculation = False
.UsedRange.EntireColumn.Delete
Sheet1.UsedRange.Copy .Cells(1, 1)
.UsedRange.Value2 = .UsedRange.Value2
.EnableCalculation = True
.EnableFormatConditionsCalculation = True
End With
Application.CutCopyMode = False
xlEnabled True
End Sub
Public Sub copyWithoutFormulas_2()
xlEnabled False
Sheet1.Copy After:=Worksheets(Worksheets.Count)
With Worksheets(Worksheets.Count).UsedRange
.Value2 = .Value2
End With
xlEnabled True
End Sub
Private Sub xlEnabled(ByVal opt As Boolean)
With Application
.EnableEvents = opt
.DisplayAlerts = opt
.ScreenUpdating = opt
.Calculation = IIf(opt, xlCalculationAutomatic, xlCalculationManual)
End With
End Sub
To force copy the source theme to the destination cells, one can do the following. Unfortunately, this method will apply the source theme to the entire destination workbook, which is OK in my situation. Not sure if it's useful for anyone else.
Sub CopyText(fromCells As Range, toCells As Range, Optional copyTheme As Boolean = False)
If copyTheme Then
Dim fromWorkbook As Workbook
Dim toWorkbook As Workbook
Dim themeTempFilePath As String
Set fromWorkbook = fromCells.Worksheet.Parent
Set toWorkbook = toCells.Worksheet.Parent
themeTempFilePath = Environ("temp") & "\" & fromWorkbook.Name & "Theme.xml"
fromWorkbook.Theme.ThemeFontScheme.Save themeTempFilePath
toWorkbook.Theme.ThemeFontScheme.Load themeTempFilePath
fromWorkbook.Theme.ThemeColorScheme.Save themeTempFilePath
toWorkbook.Theme.ThemeColorScheme.Load themeTempFilePath
End If
Set toCells = toCells.Cells(1, 1).Resize(fromCells.Rows.Count, fromCells.Columns.Count)
fromCells.Copy
toCells.PasteSpecial Paste:=xlPasteFormats
toCells.PasteSpecial Paste:=xlPasteColumnWidths
toCells.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Application.CutCopyMode = False
End Sub