用Office VBA实现多控件一次性组合

最近要做个项目,通过Office VBA来自动生成一系列的控件(包括文本框、直线等),并将这些控件组合在一起(这在Office里很好实现,只要选中这些控件,使用上下文菜单里的组合菜单项即可)。最开始的代码如下:Dimelement1,element2DimiAsIntegerSetelement1=NothingSetelement2=NothingFori=0To7Setelement1=Application.ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal,i*30,30,25,25)IfNot(element2IsNothing)ThenActiveDocument.Shapes.Range(Array(element1.Name,element2.Name)).SelectSelection.ShapeRange.Group.SelectSetelement2=Selection.ShapeRangeElseSetelement2=element1EndIfNexti 上面的代码生成了8个TextBox,将其两个为一组进行组合。这样做虽然从技术上没问题。但是如果生成的TextBox很多的话,如1000个,就会很慢。主要把时间消耗在了是用VBA进行组合操作上。因此,只要将组合的方式改为将所有控件都选中,然后组合一次就可以解决这个问题。在上面的代码中,使用了Array函数生成了Variant类型的数组。而使用Array函数是无法根据实际需要生成实际大小的数组的。因此,需要使用dim来定义这个数组,代码如下:Dimelements(0To7)AsVariantDimiAsIntegerFori=0To7 elements(i)=Application.ActiveDocument.Shapes. AddTextbox(msoTextOrientationHorizontal,i*30,30,25,25).NameNextiActiveDocument.Shapes.Range(elements).SelectSelection.ShapeRange.Group.Select应使用Dim elements(数组上标 to数组下标)的形式,不能使用Dim elements(数组下标)的形式。如上面的数组定义代码不能写成Dim elements(7) as Variant。如果在程序运行时改变数组的大小,可以使用如下的代码:Dimelements(0To7)AsVariantDimnewElementsAsVariantDimiAsIntegerFori=0To7 elements(i)=Application.ActiveDocument.Shapes. AddTextbox(msoTextOrientationHorizontal,i*30,30,25,25).NameNextinewElements=elementsReDimPreservenewElements(0To10)AsVariantFori=8To10 newElements(i)=Application.ActiveDocument.Shapes. AddTextbox(msoTextOrientationHorizontal,i*30,200,25,25).NameNextiActiveDocument.Shapes.Range(newElements).SelectSelection.ShapeRange.Group.Select 要注意的是,在使用Redim时,不能使用已经指定类型的数组,而需要将这个数组放到Variant变量中。如不能使用如下的代码来增加数组长度:ReDimPreserveelements(0To10)AsVariant

李宁的极客世界

生命不在长而在于好,只要每一次尽力的演示,都值得鼓励与喝采。

用Office VBA实现多控件一次性组合

相关文章:

你感兴趣的文章:

标签云: