excel VBA -范围到jpg图片

new9mtju  于 2023-03-20  发布在  其他
关注(0)|答案(4)|浏览(282)

我正在尝试从Excel中的特定范围获取jpg文件
我现在正在
1004 1004_Worksheet对象的Range方法出现运行时错误。
下面是我的代码:

Sub Export()

Dim ws As Worksheet
Dim Rng As Range
Dim Chrt As Chart

Set ws = ActiveSheet
Set Rng = Range("B2:H11")

ws.Range(Rng).CopyPicture
Set Chrt = Charts.Add

With Chrt
    .Paste
    .Export FileName = "Case.jpg", Filtername:="JPG"
End With

End Sub
mi7gmzs6

mi7gmzs61#

主要的错误@J_Lard已经在他的评论中提到了。
但是我会使用ChartObject而不是Chart工作表。通过这个,你可以确定输出的大小,而不是在图片中获得整个图表区域。
使用F8步骤时,粘贴和导出将正常工作,真实的运行时,需要激活ChartObject

Sub Export()

 Dim oWs As Worksheet
 Dim oRng As Range
 Dim oChrtO As ChartObject
 Dim lWidth As Long, lHeight As Long

 Set oWs = ActiveSheet
 Set oRng = oWs.Range("B2:H11")

 oRng.CopyPicture xlScreen, xlPicture
 lWidth = oRng.Width
 lHeight = oRng.Height

 Set oChrtO = oWs.ChartObjects.Add(Left:=0, Top:=0, Width:=lWidth, Height:=lHeight)

 oChrtO.Activate
 With oChrtO.Chart
  .Paste
  .Export Filename:="Case.jpg", Filtername:="JPG"
 End With

 oChrtO.Delete

End Sub

如果未指定路径,Case.jpg将保存在默认保存位置。这可能是您的用户文档目录C:\Users\YourName\Documents\

qlckcl4x

qlckcl4x2#

以下是如何在与工作簿相同的路径中导出:

Sub Export()
Dim ws As Worksheet
Dim Rng As Range
Dim Chrt As Chart
Dim ExportPath As String

Set ws = ActiveSheet
Set Rng = ws.Range("B2:H11")
ExportPath = ThisWorkbook.Path & "\Case.jpg"

Set Chrt = ThisWorkbook.Charts.Add
Rng.CopyPicture xlScreen, xlBitmap   

With Chrt
    .Paste
    .Export FileName:=ExportPath, Filtername:="JPG"
End With
End Sub
mcvgt66p

mcvgt66p3#

我不得不加上
应用程序。等待(现在+时间值(“0:00:15”))

pqwbnv8z

pqwbnv8z4#

我的Excel VBA解决方案

  1. range.Select
  2. range.CopyPicture
    1.贴上去
    1.剪切保存到系统剪贴板(关键点)
    1.在一行中创建窗口powershell命令
    1.通过Shell执行powershell
Sub 巨集1()
        PicDir = ActiveWorkbook.Path & "\"
        PicFile = Format(Now(), "hh-mm") & ".png"
        Sheets("工作表1").Select
        Range("Q1:U10").CopyPicture Appearance:=xlScreen, Format:=xlPicture '複製範圍成圖檔
        ActiveSheet.Paste '要利用這動作-1,才會真的存到 Clipboard
        ActiveSheet.Shapes.Range(Array(Selection.ShapeRange.Name)).Select '選剛貼上的 Shape
        Selection.Cut '要利用這動作-2,才會真的存到 Clipboard
        sPSCmd = "powershell $img = get-clipboard -format image ; $img.Save('" & PicDir & PicFile & "')" '把 Clipboard 內容存成圖檔的 PowerShell
        RetVal = Shell(sPSCmd, 0) '無聲無息的執行
    End Sub

相关问题