我正处于需要VBA解决方案来为每行数据创建某些Excel图表的情况。到目前为止,我已经成功地制定了一个非常基本的解决方案,但现在我发现自己处于一个我无法继续前进的地步。
我有以下代码(" ark" =" sheet"):
Sub CreateColumnClustered()
'variable declaration
Dim i As Long
Dim LastRow As Long
Dim LastColumn As Long
Dim chrt As Chart
'last row used
LastRow = Sheets("Ark1").Range("A65536").End(xlUp).Row
'last column used
LastColumn = Sheets("Ark1").Range("A1").End(xlToRight).Column
'Looping from row nr. 2 to last row
For i = 2 To LastRow
'Select Ark 2 where charts will be inserted
Sheets("Ark2").Select
'Clear cell selection
Cells(1, 1).Select
'Add charts to ark
Set chrt = Sheets("Ark2").Shapes.AddChart.Chart
'chart type
chrt.ChartType = xlColumnClustered
'chart template
chrt.ApplyChartTemplate ( _
"PATH_TO_CHART_TEMPLATE")
'establish data source
With Sheets("Ark1")
chrt.SetSourceData Source:=.Range(.Cells(i, 1), .Cells(i, LastColumn))
chrt.SeriesCollection(1).XValues = "='Ark1'!$B$1:$G$1"
End With
'anchor position of charts
chrt.ChartArea.Left = 1
chrt.ChartArea.Top = (i - 2) * chrt.ChartArea.Height
Next
End Sub
这适用于最终用户,但他们无法指定自己的模板。因此,我正在寻找能够帮助我为最终用户指定自己的.crtx文件以便与宏一起使用的方法的任何人。
我真的想避免创建多个宏,每个宏都有自己的硬编码模板文件。
答案 0 :(得分:-1)
编辑:我最终使用Application.GetOpenFilename
并将该输出作为ApplyChartTemplate
的字符串传递
这是最终代码:(注意" PATH_TO_DIR"需要更改为您想要使用的任何(如果有的话)自定义路径)
Sub Select_File_Or_Files_Windows()
Dim SaveDriveDir As String
Dim MyPath As String
Dim Fname As String
Dim i As Long
Dim LastRow As Long
Dim LastColumn As Long
Dim chrt As Chart
' Save the current directory.
SaveDriveDir = CurDir
' Set the path to the folder that you want to open.
' MyPath = Application.DefaultFilePath
' You can also use a fixed path.
MyPath = "PATH_TO_DIR"
' Change drive/directory to MyPath.
ChDrive MyPath
ChDir MyPath
' Open GetOpenFilename with the file filters.
Fname = Application.GetOpenFilename
' Change drive/directory back to SaveDriveDir.
ChDrive SaveDriveDir
ChDir SaveDriveDir
'Find the last used row
LastRow = Sheets("Ark1").Range("A65536").End(xlUp).Row
'Find the last used column
LastColumn = Sheets("Ark1").Range("A1").End(xlToRight).Column
'Looping from second row till last row which has the data
For i = 2 To LastRow
'Sheet 2 is selected bcoz charts will be inserted here
Sheets("Ark2").Select
'Clear cell selection
Cells(1, 1).Select
'Adds chart to the sheet
Set chrt = Sheets("Ark2").Shapes.AddChart.Chart
'sets the chart type
chrt.ChartType = xlColumnClustered
chrt.ApplyChartTemplate (CStr(Fname))
'now the line chart is added...setting its data source here
With Sheets("Ark1")
chrt.SetSourceData Source:=.Range(.Cells(i, 1), .Cells(i, LastColumn))
chrt.SeriesCollection(1).XValues = "='Ark1'!$B$1:$G$1"
End With
'Left & top are used to adjust the position of chart on sheet
chrt.ChartArea.Left = 1
chrt.ChartArea.Top = (i - 2) * chrt.ChartArea.Height
Next
End Sub