从指定范围创建Excel图表

问题描述 投票:0回答:1
我有一个调用 Excel 宏的 Access 数据库,该数据库又运行下面名为

CreateGraph

 的 Excel 宏。

CreateGraph

 应该从标有“Summary”的工作表中获取 A1:D12 范围内的数据。

我明白了

下标超出范围

我引用了“Microsoft Office 16.0 对象库”和“Microsoft Excel 16.0 对象库”。

Sub CreateGraph() Dim xlApp As Object 'Excel.Application Dim xlWB As Object 'Excel.Workbook Dim xlSh As Object 'Excel.Worksheet Set xlApp = CreateObject("Excel.Application") 'New Excel.Application Set xlWB = xlApp.Workbooks.Open("X:\path_here " & Format(Date, "mm-DD-yy") & ".xlsx") Set xlSh = xlWB.Sheets("Summary") xlApp.Visible = True 'code to format the excel file BEGINS Set xlWB = ActiveWorkbook Sheets("Summary").Columns("A:D").Select ActiveSheet.Shapes.AddChart2(297, xlColumnStacked).Select ActiveChart.SetSourceData Source:=Range("Summary!$A:$D") ActiveWorkbook.Save End Sub
    
excel vba
1个回答
0
投票
首先,由于您使用的是后期绑定,因此无需设置对 Excel 对象库的引用。 其次,你的宏可以重写如下......

Sub CreateGraph() Dim xlApp As Object Dim xlWB As Object Dim xlSh As Object Dim xlShp As Object Dim xlChrt As Object Set xlApp = CreateObject("Excel.Application") 'New Excel.Application xlApp.Visible = True Set xlWB = xlApp.Workbooks.Open("X:\path_here " & Format(Date, "mm-DD-yy") & ".xlsx") Set xlSh = xlWB.Sheets("Summary") Set xlShp = xlSh.Shapes.AddChart2(297, 52) '52=xlColumnStacked Set xlChrt = xlShp.Chart xlChrt.SetSourceData Source:=xlSh.Range("$A:$D") xlWB.Save End Sub
    
© www.soinside.com 2019 - 2024. All rights reserved.