2016-03-04 375 views
0

我有一个创建图形的宏。我想让VBA从电子表格中读取一个范围,并使用水平轴标签的值。基本上,我想使这个图:添加水平轴标签 - VBA Excel

enter image description here

这个样子的(添加个月的底部)

enter image description here

谢谢!

宏:

Sub AddChartSheet() 

    'Variable declaration 
    Dim chtChart As Chart 
    Dim name1 As String 

    'Name is currently used for the title of the new tab where the chart is  created and the chart title 
    name1 = "AHU-10-8" 

    'Create a new chart. 
    Set chtChart = Charts.Add 
    With chtChart 
    '.Name is the name of the tab where the new Chart is created 
    .Name = name1 

    .ChartType = xlLine 
    'Link to the source data range. 
    .SetSourceData Source:=Sheets(3).Range("A1:B5861"), _ 
    PlotBy:=xlColumns 
    .HasTitle = True 
    .ChartTitle.Text = name1 
    .Axes(xlCategory, xlPrimary).HasTitle = True 
    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time" 
    .Axes(xlValue, xlPrimary).HasTitle = True 
    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Valve Position (-)" 

    myFileName = name1 & ".png" 
    chtChart.Export Filename:=ThisWorkbook.Path & "\" & myFileName, Filtername:="PNG" 

    End With 
End Sub 

回答

0

你可以分享你的宏或工作簿?

我不确定您是如何进行数据设置的,但可以将您为水平标签选择的数据格式更改为日期格式。或者,在VBA中,您可以将选择更改为数字格式“mmmm”,以显示月份。

Selection.NumberFormat = "mmmm" 
+0

我加在OP宏。谢谢! – Jimbo

+0

我的问题是,我不知道如何选择水平标签的数据。出现的数字是默认值。 – Jimbo

0

下面应该工作。请记住在以下代码中调整图表名称

ActiveSheet.ChartObjects("Chart 4").Activate 
ActiveChart.Axes(xlCategory).Select 
Selection.TickLabels.NumberFormat = "mmmm" 
+0

好的,现在我在x轴上获得了几个月,但是每次读取得到的月份不同。我有以下格式的日期列:2016/2/1。有没有办法使用它来获得实际的月份? 谢谢! – Jimbo

+0

你现在使用什么类型的数据?您可以通过更改您的范围来调整以使用其他日期列。 – rdt0086

+0

但这是我最初的问题。如何通过vba将范围分配给x轴标签? – Jimbo

2

调整用于日期(水平轴)的数据系列。您可以添加以下内容:

ActiveSheet.ChartObjects("Chart 15").Activate 
ActiveChart.SeriesCollection(1).XValues = "=Sheet1!$D$5:$D$19" 

注意:您首先需要选择图表并将其范围调整到您需要的范围。

也可以添加

.SeriesCollection(1).XValues = "=Sheet1!$D$5:$D$19" 

之间代码

.SetSourceData Source:=Sheets(3).Range("A1:B5861"), _ 
PlotBy:=xlColumns 

.HasTitle = True