Excel VBA:显示数字的水平轴类别,但源数据具有文本标签

我正在dynamic分配数据到图表。 数据本身也是dynamic生成的。 我的问题是,即使我的源数据包含string标签(例如Dept1,Dept2),图表在横轴上仅显示数字(1,2)。 我在图表上执行了“select数据”的手动操作,并确保“水平类别标签”包含对标签的引用。 下面的图片应该更好地解释它: 示例图像

我稍后粘贴我的VBA代码。 以下是我在表单中执行的步骤:

  1. 用户提供了一个“表单”来select要查看的数据 – 更新某些单元格中的值dynamic地从另一个工作表中获取数据并将其粘贴到我的主工作表中。 数据总是两列 – 一列包含标签,另一列包含相关的值。
  2. 当主表中的数据更新时,我会查找范围大小并将其传递到图表作为其源数据(包括标签)。
  3. 根据用户select,图表types在聚集列和行之间变化。

这里是CSV格式的示例数据。 请注意,我不传递标题。
样品1:

Dept1,2105 Dept2,1569 Dept3,1891 Dept4,265 

样品2:

 42614,693.5 42644,610.5 42675,851.5 42705,852 

样本二中,标签格式为Mmm-yydate(Sep-16至Dec-16)。

这是VBA代码:

 Sub drawGraph(viewType As String) 'This sub will be called by the sub responsible for prepping data 'Each view format needs a separate type of visualisation to be shown 'this sub will figure out which graph to show and show it Dim data As Range Dim firstRow As Long Dim lastRow As Long Dim cht As ChartObject Dim mainSheet As Worksheet Dim formats As Worksheet Dim formatRow As Long Dim formatCol As Long On Error GoTo errExit 'Hide all graph columns Set mainSheet = ThisWorkbook.Worksheets("Main Sheet") mainSheet.Select mainSheet.Range(Cells(1, 12), Cells(1, 51)).EntireColumn.Hidden = True 'View Type 1 has no graph, escape with if condition If Not viewType = "View Type 1" Then 'Pre-prepared view types (graph, text, etc.) are placed in certain hidden columns, each spanning 9 columns. 'We need to find the starting column of the view type that we need. Set formats = ThisWorkbook.Worksheets("Formats Base") formats.Select formats.Columns("A:A").Select formatRow = Selection.Find(What:=viewType, _ After:=Range("A1"), _ LookAt:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row formatCol = formats.Cells(formatRow, 4) mainSheet.Activate 'unhide 9 columns 'all graphs are designed to fit within 9 columns 'Might not be the most efficient way to do this but it's the only one I know Union(Columns(formatCol), Columns(formatCol + 1), Columns(formatCol + 2), _ Columns(formatCol + 3), Columns(formatCol + 4), Columns(formatCol + 5), _ Columns(formatCol + 6), Columns(formatCol + 7), Columns(formatCol + 8), Columns(formatCol + 9)).EntireColumn.Hidden = False 'Need to assign data to chart 'View Type 2 does not have a graph, escape with if condition If Not viewType = "View Type 2" Then mainSheet.Cells(6, 22).Value = "" Set cht = mainSheet.ChartObjects("dataGraph") Select Case viewType Case "View Type 3" cht.chart.chartType = xlColumnClustered Case "View Type 4 - Months" cht.chart.chartType = xlLine Case "View Type 5" cht.chart.chartType = xlColumnClustered End Select firstRow = 4 lastRow = mainSheet.Range("H1").CurrentRegion.Rows.Count Set data = mainSheet.Range(Cells(firstRow, 8), Cells(lastRow, 9)) cht.chart.SetSourceData Source:=data ElseIf viewType = "View Type 2" Then mainSheet.Cells(6, 22).Value = "=$I$3/$V$4" End If End If errExit: Application.ScreenUpdating = True End Sub