循环浏览工作表,同时将范围导出为图像

时间:2016-11-21 15:56:53

标签: vba excel-vba excel

我有以下VBA代码,用于将一系列单元格导出到jpeg到指定的文件夹中。我想让它遍历一个工作簿中的所有工作表。

我需要帮助在所有打开的工作簿中循环此代码。我相信我需要: Dim WS As Worksheet,然后设置一个If语句,插入下面的代码,结束if语句,然后在最后放一个Next WS让它实际循环。我的问题是,当我尝试组合我的if语句时,我一直得到91错误。对于每个WS在ThisWorkbook.Sheets如果不是WS.Name =" Sheet2"然后,我的代码如下。

以下代码一次只能在一个工作表中使用。

Sub ExportAsImage()
Dim objPic As Shape
Dim objChart As Chart
Dim i As Integer
Dim intCount As Integer
'copy the range as an image
Call ActiveSheet.Range("A1:F2").CopyPicture(xlScreen, xlPicture)
'remove all previous shapes in the ActiveSheet
intCount = ActiveSheet.Shapes.Count
For i = 1 To intCount
    ActiveSheet.Shapes.Item(1).Delete
Next i
'create an empty chart in the ActiveSheet
ActiveSheet.Shapes.AddChart
'select the shape in the ActiveSheet
ActiveSheet.Shapes.Item(1).Select
ActiveSheet.Shapes.Item(1).Width = Range("A1:F2").Width
ActiveSheet.Shapes.Item(1).Height = Range("A1:F2").Height
Set objChart = ActiveChart
'clear the chart
objChart.ChartArea.ClearContents
'paste the range into the chart
objChart.Paste
'save the chart as a JPEG
objChart.Export ("C:\Users\------\Desktop\Test\" & Range("B2").Value &     ".jpg")
'remove all shapes in the ActiveSheet
intCount = ActiveSheet.Shapes.Count
For i = 1 To intCount
    ActiveSheet.Shapes.Item(1).Delete
Next i
End Sub

1 个答案:

答案 0 :(得分:1)

将此添加到您的模块:

Sub MAIN()
    Dim sh As Worksheet
    For Each sh In Sheets
        sh.Activate
        Call ExportAsImage
    Next sh
End Sub

然后运行它。 (无需修改代码)