VBA:我试图根据单独工作表中包含的数据在主工作表上填充条形图。但是,在填充图表之前,我需要让vba按降序对数据进行排序。
我每年都会使用宏来填充排名表,但是,每次运行选定年份的宏时,都会生成条形图,而不会按降序对数据进行排序。当我尝试包含一个代码来对数据进行排序时,我通常会得到运行时错误91.
这是我目前的代码 - 有人可以帮我吗?这是我第一次使用vba。理想情况下,我想在生成图表之前对N列中的数据进行排序。谢谢。
Sub NewIssues2014()
Dim sht As Worksheet
Dim dashboard As Worksheet
Set sht = Worksheets("New Issues League Table")
Set dashboard = Worksheets("Dashboard")
ArrangerLastRow = sht.Cells(Rows.Count, 12).End(xlUp).Row
YearLastRow = sht.Cells(Rows.Count, 14).End(xlUp).Row
Sheets("New Issues League Table").Select
Range("M1:S1").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("New Issues League Table").AutoFilter.Sort.SortFields _
.Clear
ActiveWorkbook.Worksheets("New Issues League Table").AutoFilter.Sort.SortFields _
.Add Key:=Range("N1"), SortOn:=xlSortOnValues, Order:=xlDescending, _
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("New Issues League Table").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
With dashboard
dashboard.Shapes.AddChart.Select
ActiveChart.ChartType = xlBarStacked
ActiveChart.SetSourceData Source:=sht.Range("L2:L" & ArrangerLastRow & ",N2:N" & YearLastRow), PlotBy:=xlColumns
ActiveChart.Axes(xlCategory).Select
ActiveChart.Axes(xlCategory).ReversePlotOrder = True
ActiveChart.Axes(xlCategory).Crosses = xlMaximum
ActiveChart.HasTitle = True
ActiveChart.HasLegend = False
ActiveChart.ChartTitle.Text = "2014 New Issue Deals"
End With
With ActiveChart.Parent
.Height = 325
.Width = 900
.Top = 1070
.Left = Range("B94").Left
End With
End Sub
答案 0 :(得分:0)
自动过滤器在直接使用时效果很好,但在通过VBA控制时似乎相当敏感。查看https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-sort-method-excel
要使用标准排序功能,您基本上只需要从所有内容中删除“自动过滤”,并且更具体地使用您的范围参考:
Sheets("New Issues League Table").Select
Range("M1:Sx").Select 'Replace x with the last row in your table
ActiveWorkbook.Worksheets("New Issues League Table").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("New Issues League Table").Sort.SortFields _
.Add Key:=Range("N1:Nx"), SortOn:=xlSortOnValues, Order:=xlDescending, _
DataOption:=xlSortNormal 'Again, replace x with the last row in your table
With ActiveWorkbook.Worksheets("New Issues League Table").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
编辑:回复评论 -
你的With
声明有点偏。你打开它,但实际上并没有使用它。避免尽可能多地使用.Select
函数也是谨慎的 - 在大多数情况下实际上并不需要它。这会更好:
dashboard.Shapes.AddChart
With ActiveChart
.ChartType = xlBarStacked
.SetSourceData Source:=sht.Range("L2:L" & ArrangerLastRow & ",N2:N" & YearLastRow), PlotBy:=xlColumns
.Axes(xlCategory).Select
.Axes(xlCategory).ReversePlotOrder = True
.Axes(xlCategory).Crosses = xlMaximum
.HasTitle = True
.HasLegend = False
.ChartTitle.Text = "2014 New Issue Deals"
End With