在 Excel VBA 中截图并保存在单独的文件中

Take Screenshot in Excel VBA and save in a separate file

我试图通过在后台单击带有 VBA 代码的按钮,直接从 excel sheet 自动生成小型屏幕截图。情况是这样的:

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

从之前的一篇帖子中,我发现这段代码似乎可以工作,首先将上述范围的屏幕截图包含到一个新的图表表中,然后它成功地将 scrt.png 文件保存在上述位置.本质上,它成功地生成了 ChartSheet 中所选单元格区域的位图,并且还在提到的位置生成了单独的 scrt.png 文件。 但是,代码的问题在于创建的 scrt.png 文件包含整个 ChartSheet 屏幕截图。我正在寻找的只是用提到的单元格范围快照保存的文件。 试图调整代码,但没有成功。任何帮助将不胜感激。

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

非常感谢。

不使用图表 sheet,而是在常规作品上使用嵌入的图表对象sheet - 然后您可以在粘贴复制的范围图片之前调整它的大小

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