【问题标题】:Using VBA code, how to export Excel worksheets as image in Excel 2003?使用 VBA 代码,如何在 Excel 2003 中将 Excel 工作表导出为图像?
【发布时间】:2021-12-31 04:30:05
【问题描述】:

请建议将 Excel 工作表中的数据范围导出为 .jpeg 或 .png 或 .gif 格式的图像的更好方法。

【问题讨论】:

  • 你用的是什么版本的Excel,是Excel 2007,Exxel 2010?因为在最近的版本中,有一个功能 Copy...as Picture 可以使用 VBA 自动完成。
  • 我使用的是 excel 2003。

标签: vba image excel export


【解决方案1】:

你想试试下面的代码吗?我在很多个月前的某个地方在互联网上找到并使用过。

它使用 Chart 对象的 Export 函数和 Range 对象的 CopyPicture 方法。

参考文献:

【讨论】:

  • 这行对我有用:Worksheets(sSheetName).Range(oRangeToCopy).CopyPicture xlScreen, xlBitmap
  • 有没有办法提高导出图片的大小?默认大小没有提供图表的太多细节。
  • @Vivek:我只能建议你看看其他答案 - 他们可能会提供一些帮助......
【解决方案2】:

我已尝试通过多种方式改进此解决方案。现在生成的图像具有正确的比例。

Set sheet = ActiveSheet
output = "D:\SavedRange4.png"

zoom_coef = 100 / sheet.Parent.Windows(1).Zoom
Set area = sheet.Range(sheet.PageSetup.PrintArea)
area.CopyPicture xlPrinter
Set chartobj = sheet.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
chartobj.Chart.Paste
chartobj.Chart.Export output, "png"
chartobj.Delete

【讨论】:

  • 由于某种原因我收到一张空白图片。
  • @ZygD 可能PrintArea 在活动工作表上为空?
  • 我遇到了同样的问题。当我一次单步执行代码时,图像工作正常,但如果我只是运行它,图像被创建但显示为空白。还尝试了一段时间,但没有帮助。 @Winand
  • @JoeK 如果删除最后两行(.export 和 .delete)会怎样?图片是空白的吗?
【解决方案3】:

谢谢大家!我稍微修改了 Winand 的代码以将其导出到用户的桌面,无论谁在使用工作表。我在代码中将我的想法归功于我的想法(感谢凯尔)。

Sub ExportImage()


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's 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"

'Export print area as correctly scaled PNG image, courtasy of Winand
zoom_coef = 100 / Sheet.Parent.Windows(1).Zoom
Set area = Sheet.Range(Sheet.PageSetup.PrintArea)
area.CopyPicture xlPrinter
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)

End Sub

【讨论】:

    【解决方案4】:

    Winand,质量对我来说也是一个问题,所以我这样做了:

    For Each ws In ActiveWorkbook.Worksheets
        If ws.PageSetup.PrintArea <> "" Then
            'Reverse the effects of page zoom on the exported image
            zoom_coef = 100 / ws.Parent.Windows(1).Zoom
            areas = Split(ws.PageSetup.PrintArea, ",")
            areaNo = 0
            For Each a In areas
                Set area = ws.Range(a)
                ' Change xlPrinter to xlScreen to see zooming white space
                area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
                Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
                chartobj.Chart.Paste
                'scale the image before export
                ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
                ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
                chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
                chartobj.delete
                areaNo = areaNo + 1
            Next
        End If
    Next
    

    看这里:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/

    【讨论】:

    • 我知道你在这里做了什么。)您可以通过修改“zoom_coef = ... * 3”行来获得相同的结果
    • 不,如果我这样做,图像会更小并有额外的空白
    • 嗯,我在发帖前检查了 excel2013。您能否将绝对为您提供带有空格的图像的代码粘贴到二进制文件中? (有时我希望 SO 成为一个论坛。)
    • 首先我在 2010 年,问题指的是 2003 年。 xlScreen :将缩放,xlPrinter :将调整大小。我的代码我省略了 xlPrinter,所以它默认为 xlScreen。但是您的代码旨在抵消屏幕左下角对屏幕缩放的调整效果。
    • 但是如果缩放为 100%,它会按照你说的那样做。我们需要结合缩放和缩放来保证导出的质量,而不管工作表的缩放程度如何。
    【解决方案5】:

    没有图表的解决方案

    Function SelectionToPicture(nome)
    
    'save location ( change if you want )
    FName = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & nome & ".jpg"
    
    'copy selection and get size
    Selection.CopyPicture xlScreen, xlBitmap
    w = Selection.Width
    h = Selection.Height
    
    
    
    With ThisWorkbook.ActiveSheet
    
        .Activate
    
        Dim chtObj As ChartObject
        Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
        chtObj.Name = "TemporaryPictureChart"
    
        'resize obj to picture size
        chtObj.Width = w
        chtObj.Height = h
    
        ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
        ActiveChart.Paste
    
        ActiveChart.Export FileName:=FName, FilterName:="jpg"
    
        chtObj.Delete
    
    End With
    End Function
    

    【讨论】:

      【解决方案6】:

      如果您向 Ryan Bradley 代码添加选择并保存到工作簿路径,这将更具弹性:

       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's 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
      

      【讨论】:

        【解决方案7】:

        根据 Philip 提供的链接,我得到了这个工作

        Worksheets("Final Analysis Sheet").Range("A4:G112").CopyPicture xlScreen, xlBitmap
        
            Application.DisplayAlerts = False
            Set oCht = Charts.Add
            With oCht
                .Paste
                .Export Filename:="C:\FTPDailycheck\TodaysImages\SavedRange.jpg", Filtername:="JPG"
                .Delete
            End With
        

        【讨论】:

          【解决方案8】:

          有一种更直接的方法可以将范围图像导出到文件,而无需创建临时图表。它利用 PowerShell 将剪贴板保存为 .png 文件。

          使用 vba CopyPicture 命令将范围作为图像复制到剪贴板很简单,如其他一些答案所示。

          保存剪贴板的 PowerShell 脚本只需要两行,正如 thom schumacher 在Save Image from clipboard using PowerShell 中所指出的那样。

          VBA 可以启动一个 PowerShell 脚本并等待它完成,正如 Asam 在Wait for shell command to complete 中所指出的那样。

          将这些想法放在一起,我们得到以下例程。我仅在 Windows 10 下使用 Office 2010 版本的 Excel 对此进行了测试。请注意,有一个内部常量 AidDebugging 可以设置为 True 以提供有关例程执行的额外反馈。

          Option Explicit
          
          ' This routine copies the bitmap image of a range of cells to a .png file.
          ' Input arguments:
          '    RangeRef -- the range to be copied. This must be passed as a range object, not as the name
          '                or address of the range.
          '    Destination -- the name (including path if necessary) of the file to be created, ending in
          '                the extension ".png". It will be overwritten without warning if it exists.
          '    TempFile -- the name (including path if necessary) of a temporary script file which will be
          '                created and destroyed. If this is not supplied, file "RangeToPNG.ps1" will be
          '                created in the default folder. If AidDebugging is set to True, then this file
          '                will not be deleted, so it can be inspected for debugging.
          ' If the PowerShell script file cannot be launched, then this routine will display an error message.
          ' However, if the script can be launched but cannot create the resulting file, this script cannot
          ' detect that. To diagnose the problem, change AidDebugging from False to True and inspect the
          ' PowerShell output, which will remain in view until you close its window.
          
          Public Sub RangeToPNG(RangeRef As Range, Destination As String, _
                                Optional TempFile As String = "RangeToPNG.ps1")
          Dim WSH As Object
          Dim PSCommand As String
          Dim WindowStyle As Integer
          Dim ErrorCode As Integer
          Const WaitOnReturn = True
          Const AidDebugging = False ' provide extra feedback about this routine's execution
            ' Create a little PowerShell script to save the clipboard as a .png file
            ' The script is based on a version found on September 13, 2020 at
            '    https://stackoverflow.com/questions/55215482/save-image-from-clipboard-using-powershell
             Open TempFile For Output As #1
             If (AidDebugging) Then ' output some extra feedback
                Print #1, "Set-PSDebug -Trace 1" ' optional -- aids debugging
             End If
             Print #1, "$img = get-clipboard -format image"
             Print #1, "$img.save(""" & Destination & """)"
             If (AidDebugging) Then ' leave the PowerShell execution record on the screen for review
                Print #1, "Read-Host -Prompt ""Press <Enter> to continue"" "
                WindowStyle = 1 ' display window to aid debugging
             Else
                WindowStyle = 0 ' hide window
             End If
             Close #1
            ' Copy the desired range of cells to the clipboard as a bitmap image
             RangeRef.CopyPicture xlScreen, xlBitmap
            ' Execute the PowerShell script
             PSCommand = "POWERSHELL.exe -ExecutionPolicy Bypass -file """ & TempFile & """ "
             Set WSH = VBA.CreateObject("WScript.Shell")
             ErrorCode = WSH.Run(PSCommand, WindowStyle, WaitOnReturn)
             If (ErrorCode <> 0) Then
                MsgBox "The attempt to run a PowerShell script to save a range " & _
                       "as a .png file failed -- error code " & ErrorCode
             End If
             If (Not AidDebugging) Then
               ' Delete the script file, unless it might be useful for debugging
                Kill TempFile
             End If
          End Sub
          
          ' Here's an example which tests the routine above.
          Sub Test()
             RangeToPNG Worksheets("Sheet1").Range("A1:F13"), "E:\Temp\ExportTest.png"
          End Sub
          

          【讨论】:

          • 谢谢你。让它适用于受保护的工作表,而其他人则不能。以及图像质量的结果。
          • 顺便说一句,为什么脚本会从保存的图像中删除一点左侧部分?像这样的例子:工作表视图 - i.imgur.com/HFrRxod.png。保存的图像变为:i.imgur.com/YWJFjGO.png.
          • @amein -- 我假设答案是“为什么......?”是“这是微软的错误”。我也注意到了——外部单元格边界有时不包含在图像中。我通过在目标范围周围添加非常窄的空行和列来解决它,然后将稍微放大的范围(包括空白部分)输出为图像。这会导致所有有趣的单元格边界变成内部边界,因此它们是最终图像的一部分。
          • 谢谢!知道了!按照建议修复了这个问题。
          【解决方案9】:

          这给了我最可靠的结果:

          Sub RangeToPicture()
            Dim FileName As String: FileName = "C:\file.bmp"
            Dim rPrt As Range: Set rPrt = ThisWorkbook.Sheets("Sheet1").Range("A1:C6")
            'Add a Zoom to increase the resolution of the image.          
            ActiveWindow.Zoom = 300
            
            Dim chtObj As ChartObject
            rPrt.CopyPicture xlScreen, xlBitmap
            Set chtObj = ActiveSheet.ChartObjects.Add(1, 1, rPrt.Width, rPrt.Height)
            chtObj.Activate
            ActiveChart.Paste
            ActiveChart.Export FileName
            chtObj.Delete
            'Reset Zoom to innitial zoom of the image.          
            ActiveWindow.Zoom = 100
          End Sub
          

          【讨论】:

          • 这个在 2020 年对我有用,其他很多都没有。
          猜你喜欢
          • 2016-12-06
          • 2010-09-18
          • 2021-04-22
          • 2013-03-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-27
          • 2016-08-04
          • 2014-02-12
          相关资源
          最近更新 更多