首页 文章

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

提问于
浏览
0

我有以下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 回答

  • 1

    将其添加到您的模块:

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

    并运行它 . (无需修改代码)

相关问题