VBA - Range to jpg picture

后端 未结 2 1862
暗喜
暗喜 2020-12-03 13:19

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

I\'m currently getting the

1004 Runtime error on Range method from _Worksheet ob

2条回答
  •  旧时难觅i
    2020-12-03 13:55

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

    But I would use ChartObject rather than a Chart sheet. Whith this you can determine the size of the output instead of getting the whole chart area in the picture.

    And while using F8 step the paste and export will work, while real time run, the ChartObject needs to be activated.

    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.jpg will be saved in default save location. This is probably your user documents directory C:\Users\YourName\Documents\

提交回复
热议问题