excel下拉列表怎么添加?excel下拉列表设置的简单方法
本节介绍一下ControlFormat对象,严格来说这个对象是对应于Excel中的ListBox对象的一些属性和方法,为什么不以ListBox来返回,就不太清楚了。
总之,要对Excel表中的ListBox对象操作就这么做就行了。
那么,如何得到ControlFormat对象呢?
用下面的方法:
dim xCF as Object
Set xCF=Shapes(i).ControlsFormat
对象xCF就是一个ControlFormat对象,其中i代表了此Shape的Index值。
这就有点不可想像了,Shape是Excel表绘图层中的对象,例如自选图形、任意多边形、OLE 对象或图片,此处就代表了一个OLE对象,即ListBox。
有点乱,但要了解一下Shape对象,如下图所示,有按钮对象,下拉列表和文本框对象,都 属于Shapes对象合集。
可以使用Shape对象的ContrlFormat来返回ContrlFormat对象。
当我们得到这个ContrlFormat对象之后,就可以对下拉列表框进行各种添加删除操作了。
ContrlFormat对象有四个方法:Additem、List、RemoveAllitems、Removeitem
懂基本英语就基本明白这四种方法的功能了,这里不做过多介绍,具体可参考下面的代码进行对号。
更加重要的是ContrlFormat的属性,一共有17个,属性就是用一些固定的参数来进行设置,可以使下拉列表框更加符合要求,目的很简单。
下面,用实例来证明一下我们通过代码如何实现对下拉列表的添加、修改、删除等等操作。
添加列表框
Private Sub AddListBox()DelListbox '删除除列表框Dim xlobj As Object'添加列表框Set xlobj = Me.Shapes.AddFormControl(xlListBox, Range("E3").Left, Range("E3").Top, 200, 350)Dim xFormat As ObjectSet xFormat = xlobj.ControlFormat '返回列表对象xFormat.RemoveAllItems '清除列表内容xFormat.ListFillRange = Range("C4:C20").Address'设置列表区域Set xFormat = NothingSet xlobj = NothingEnd Sub
返回列表值
Private Sub ShowListValue()Dim xShape As ShapeFor Each xShape In Me.Shapes If xShape.Type = 8 Then MsgBox xShape.ControlFormat.List(xShape.ControlFormat.ListIndex) End IfNext xShapeEnd Sub
给列表框添加列表
Private Sub AddListItems()Dim xShape As ShapeFor Each xShape In Me.Shapes'遍历Shapes If xShape.Type = 8 Then'如果是列表 xShape.ControlFormat.RemoveAllItems'清除所有列表值 For i = 4 To 7 xShape.ControlFormat.AddItem Range("B" & i).Value'添加列表 Next i End IfNext xShapeEnd Sub
如上代码,根据ContrlFormat的四个方法和属性可实现所有对列表框的添加删除修改功能。
这样,就大大地增加了Excel工作表的一些使用功能。