使用Excel列表框中的选定值来表示图例

时间:2014-08-24 04:04:14

标签: excel vba excel-vba

我正在尝试将list box中的Excel中的选定值传递到图表中的图例。具体来说,我有以下格式的某些公司的数据

enter image description here

我还有一个列表框globalList,其中包含可以选择的公司名称。选定的公司'然后使用VBA将数据传递到图表上。

enter image description here

但是,我遇到的问题包括以下几个部分:

初始化变量以保存在globalList中选择的值

listMax = globalList.ListCount - 1
`this creates the upper bound for the list box

For i = 0 To (globalList.ListCount - 1)
    If globalList.Selected(i) = True Then
        companiesSelected = companiesSelected + 1
    End If
    If i = listMax Then
    Exit For
    End If
Next i
`the above is used to retrieve the number of companies that have been selected by a user - whether =0 or > 0

Dim myLegend() As String
ReDim myLegend(0 To (globalList.ListCount - 1))
For i = 0 To (globalList.ListCount - 1)
    If globalList.Selected(i) = True Then
        myLegend(i) = globalList.List(i)
    End If
    If i = listMax Then
    Exit For
    End If
Next i
`this is the array object in which I intend to store company names selected in the list box.

问题在于,即使上面创建了myLegend字符串数组,它也包含用户可能未在列表框中选择的公司的空数组项。 即使我能够从阵列中删除这些空项目,也会出现以下问题

将保留的值从我的变量传递到我的图表

    For i = 1 To companiesSelected
    myChart.SeriesCollection(i).Name = myLegend(i)
    Next i

这里的问题是myLegend数组从0开始,而SeriesCollection似乎从1开始。所以我无法将所选项的字符串值传递给我的图表的图例'第

有人可以指出如何规避这些问题吗? 非常感谢提前!

1 个答案:

答案 0 :(得分:1)

这是一个将所选项目提取到one-based String数组(没有空项)的代码:

Dim i           As Integer
Dim iCount      As Integer
Dim myLegend()  As String

iCount = 0
With globalList

    ReDim myLegend(1 To .ListCount)
    For i = 0 To .ListCount - 1
        If .Selected(i) = True Then
            iCount = iCount + 1
            myLegend(iCount) = .List(i)
        End If
    Next i

End With

If iCount > 0 Then
    ReDim Preserve myLegend(1 To iCount)
Else
    ReDim myLegend(1 To 1)
    myLegend(1) = "Nothing here!"
End If