This article is original. If you need to reprint it, please indicate the author and the source. Thank you!
Recently, I want to create a project throughOffice VBATo automatically generate a series of controls (including text boxes, straight lines, etc.), and combine these controls (OfficeYou only need to select these controls and use the combined menu items in the context menu ). InitialCodeAs follows:
Dim Element1, element2
Dim I As Integer
Set Element1 = Nothing
Set Element2 = Nothing
For I = 0 To 7
Set Element1 = Application. activedocument. shapes. addtextbox (msotextorientationhorizontal, I * 30 , 30 , 25 , 25 )
If Not (Element2 Is Nothing ) Then
Activedocument. shapes. Range (Array (element1.name, element2.name). Select
Selection. shaperange. Group. Select
Set Element2 = Selection. shaperange
Else
Set Element2 = Element1
End If
Next I
The above code generates 8 Items Textbox , And combine the two into a group. Although there is no technical problem in this way. However, if Textbox Many words, such 1000 It will be very slow. It is mainly used to consume time. VBA In combination. Therefore, you only need to select all controls in the combination mode and then combine them once to solve this problem. In the above Code Array Function generated Variant Type array. And use Array The function cannot generate an array of the actual size based on actual needs. Therefore, you must use Dim To define this array, the Code is as follows:
Dim Elements ( 0 To 7 ) As Variant
Dim I As Integer
For I = 0 To 7
Elements (I) = Application. activedocument. shapes.
Addtextbox (msotextorientationhorizontal, I * 30 , 30 , 25 , 25 ). Name
Next I
Activedocument. shapes. Range (elements). Select
Selection. shaperange. Group. Select
ApplicableDim elements (Array taggingToArray subscript)Cannot be used.Dim elements (Array subscript). The preceding array definition Code cannot be writtenDim elements (7) as Variant.
IfProgramRun the following code to change the array size:
Dim Elements ( 0 To 7 ) As Variant
Dim Newelements As Variant
Dim I As Integer
For I = 0 To 7
Elements (I) = Application. activedocument. shapes.
Addtextbox (msotextorientationhorizontal, I * 30 , 30 , 25 , 25 ). Name
Next I
Newelements=Elements
Redim PreserveNewelements (0 To 10)AsVariant
For I = 8 To 10
Newelements (I) = Application. activedocument. shapes.
Addtextbox (msotextorientationhorizontal, I * 30 , 200 , 25 , 25 ). Name
Next I
Activedocument. shapes. Range (newelements). Select
Selection. shaperange. Group. Select
Note thatRedimYou cannot use an array of the specified type.VariantVariable. If the following code cannot be used to increase the length of an array:
Redim Preserve Elements ( 0 To 10 ) As Variant