VBA - 范围到jpg图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42091390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:03:24  来源:igfitidea点击:

VBA - Range to jpg picture

excelvbaexcel-vba

提问by IAIAIA

I'm trying to get a jpg file from a specific range in excel

我正在尝试从 excel 中的特定范围获取 jpg 文件

I'm currently getting the

我目前得到

1004 Runtime error on Range method from _Worksheet object.

1004 来自 _Worksheet 对象的 Range 方法的运行时错误。

This is what my code looks like:

这是我的代码的样子:

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

回答by Axel Richter

The main error has @J_Lard mentioned already in his comment.

主要错误已经在他的评论中提到了@J_Lard。

But I would use ChartObjectrather than a Chartsheet. Whith this you can determine the size of the output instead of getting the whole chart area in the picture.

但我会使用ChartObject而不是一张Chart纸。有了这个,您可以确定输出的大小,而不是获取图片中的整个图表区域。

And while using F8step the paste and export will work, while real time run, the ChartObjectneeds to be activated.

并且在使用F8step 时粘贴和导出将起作用,而在实时运行时,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

If path is not specified, the Case.jpgwill be saved in default save location. This is probably your user documents directory C:\Users\YourName\Documents\

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

回答by R3uK

Here is how to export in the same path as the workbook :

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

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