按钮上的VBA导出图表数组单击

时间:2014-10-17 17:58:05

标签: vba

 Sub onButtonClick()

Dim source As Worksheet, target As Worksheet
Set source = Workbooks("End Market Monitor.xlsm").Worksheets("Aero Graphs")
Set target = Sheet1

Dim ws As Worksheet
Dim title_name As String, search As String



search = ActiveCell.Offset(0, -5).Value
ReDim chartArray(1 To source.ChartObjects.Count) As Chart
For i = 1 To source.ChartObjects.Count
    title_name = source.ChartObjects(i).Chart.ChartTitle.Text
    counter = 1
    If InStr(title_name, search) > 0 Then
        Set chartArray(counter) = source.ChartObjects(i).Chart
        counter = counter + 1
    End If

Next
Set wsTemp = Sheets.Add

    tp = 10

    With wsTemp
        For n = 1 To UBound(chartArray)
            chartArray(n).CopyPicture
            wsTemp.Range("A1").PasteSpecial
            Selection.Top = tp
            Selection.Left = 5
            tp = tp + Selection.Height + 50
        Next
    End With

    wsTemp.ExportAsFixedFormat Type:=xlTypePDF, Filename:=NewFileName, Quality:=xlQualityStandard, _
           IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

我遇到搜索变量问题。我一直得到对象定义错误,我不明白为什么......我应该使用Cells.Offset吗?

另外,当我遍历图表数组时,我无法使用for循环,因此我不得不从1循环到数组的上限。这可行吗?

1 个答案:

答案 0 :(得分:0)

由于ActiveCell.Offset(0,-5)正试图选择一个不存在的单元格,因此弹出了对象定义的错误。如果ActiveCell位于A,B,C,D或E列,它将显示此错误,因为A之前没有列。也许更具体,然后是#34; ActiveCell"。

至于循环图表,以下内容应该有效:

Dim ChartObj as Chartobject
For each ChartObj in Source.ChartObjects
    ....
Next ChartObj