我的问题涉及图表和排除空白范围内的单元格。我有一个程序,最终将从数据表拉到另一张表,所以我可以从我正在使用的两个数据(日期和数量)制作一个图表。我的问题是我的范围长度会根据数据的输入值而改变。因此,一些imputs将具有B2:C5的范围,而其他的将具有与B2:C40一样长的范围。这就是我目前要创建的图表:
Sub ChartMagic()
Dim cht As Chart
Worksheets(3).Shapes.AddChart.Select
With Worksheets(3).ChartObjects(1)
.Left = Range("A9").Left
.Top = Range("A9").Top
End With
With ActiveChart
.SetSourceData Source:=Worksheets(4).Range("B2:C100"), PlotBy:=xlColumns
.ChartType = xlLine
.HasTitle = False
.Axes(xlCategory).HasTitle = True
.Axes(xlCategory).AxisTitle.Text = "Date"
.Axes(xlValue).HasTitle = True
.Axes(xlValue).AxisTitle.Text = "Bin Quantity"
.HasLegend = False
End With
End Sub
我遇到的问题不在于我没有创建图表,而是我的图表包含所有空白的单元格。基本上,我想要实现的是无论我带到“B2:C100”的单元格范围,它都会排除空白单元格并创建一个只包含有值数据的图表。
答案 0 :(得分:0)
我做了一些其他更改,以避免依赖于选择/激活方法(请参阅here了解原因)。
从评论中修改,假设从B2:C2开始的连续数据范围。
Sub ChartMagic()
Dim cht As Chart
Dim chtDataRange as Range
'## Define the range to represent in the chart, this is dynamic and assumes that
' the data is contiguous (i.e., no blank rows in the middle, only at the end)
With Worksheets(4)
Set chtDataRange = .Range("B2:C2", .Range("B2:C2").End(xlDown))
End With
'## Made some modifications to avoid using Select/Activate methods
' use the variable "cht" to represent the Chart:
Set cht = Worksheets(3).Shapes.AddChart
With cht
.Left = Range("A9").Left
.Top = Range("A9").Top
'## Use the range variable instead of an absolute reference:
.SetSourceData Source:=chtDataRange, PlotBy:=xlColumns
.ChartType = xlLine
.HasTitle = False
.Axes(xlCategory).HasTitle = True
.Axes(xlCategory).AxisTitle.Text = "Date"
.Axes(xlValue).HasTitle = True
.Axes(xlValue).AxisTitle.Text = "Bin Quantity"
.HasLegend = False
End With
End Sub