vba 如何使用 ListBox.ListIndex

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15560437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:14:13  来源:igfitidea点击:

How to use ListBox.ListIndex

excelexcel-vbavba

提问by Russ Urquhart

I am going through a single select list box, to determine which series to select. The previous developer on this did the following:

我正在浏览一个选择列表框,以确定要选择的系列。之前的开发人员做了以下工作:

For i = 0 To ListBox4.ListCount - 1
   If ListBox4.Selected(i) Then
      Series_Msg = Series_Msg & ListBox4.List(i) & vbNewLine
      ActiveChart.SeriesCollection(i + 1).Select

      'other commands

  Next i

In an attempt to clean up his code, i tried to do something like the following:

为了清理他的代码,我尝试执行以下操作:

   If ListBox4.ListIndex <> -1 then

       ActiveChart.SeriesCollection(ListBox4.ListIndex + 1).Select

But i get an object required error. I tried declaring i as an object and assigning it the ListIndex value but that didn't work.

但是我收到了一个需要对象的错误。我尝试将 i 声明为一个对象并为其分配 ListIndex 值,但这不起作用。

Can anyone suggest how i can do this without the loop? I can't believe that this loop is necessary.

谁能建议我如何在没有循环的情况下做到这一点?我不敢相信这个循环是必要的。

Any help is greatly appreciated!

任何帮助是极大的赞赏!

Russ

拉斯

回答by Parrish Husband

Make sure you've got the chart properly selected:

确保您已正确选择图表:

Worksheets("Sheet1").ChartObjects("Chart 1").Activate

If ListBox4.ListIndex <> -1 Then
    Series_Msg = Series_Msg & ListBox4.List(ListBox4.ListIndex, 0)
    ActiveChart.SeriesCollection(ListBox4.ListIndex + 1).Select
End If

回答by David Zemens

This code works fine for me, provided there is an ActiveChart. Add some handling to ensure that ActiveChart is not Nothing. Otherwise, you will get that error, Object Variable or With Block not set.

这段代码对我来说很好用,只要有一个ActiveChart. 添加一些处理以确保 ActiveChart 不是 Nothing。否则,你会得到那个错误,Object Variable or With Block not set

Sub UserForm_Activate()
    ListBox1.AddItem "First"
    ListBox1.AddItem "Second"
    ListBox1.AddItem "Third"
End Sub

Private Sub ListBox1_AfterUpdate()
Dim i As Integer

If ActiveChart Is Nothing Then 
    MsgBox "There is no ActiveChart!"
    Exit Sub
End If

i = ListBox1.ListIndex + 1

ActiveChart.SeriesCollection(i).Select
'Alternatively, you can ignore "i" and just use ActiveChart.SeriesCollection(ListBox1.ListIndex+1).Select

Unload UserForm1

End Sub

回答by Felipe Costa Gualberto

Trye using: ActiveChart.SeriesCollection(ListBox4.List(ListBox4.ListIndex)).Select

尝试使用: ActiveChart.SeriesCollection(ListBox4.List(ListBox4.ListIndex)).Select