VBA创建多个文本框后如何选中全部并分组?
如何在VBA创建文本框后选中所有文本框并分组?
我有一个在工作表中创建n个文本框的VBA子程序
CreateShapes,代码如下:Sub CreateShapes() Dim sOrd As String Dim n As Integer Const iBr = 67 sOrd = Selection.Text For n = 1 To Len(sOrd) ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 50 + iBr * n, 150 _ , 200, 70).Select Selection.ShapeRange(1).TextFrame2.TextRange.Characters.Text = Mid(sOrd, n, 1) Next n End Sub子程序执行完毕后,仅最后一个文本框处于选中状态。我尝试使用
ShapeRange但未成功,请问如何选中所有n个文本框以进行分组?
原代码的问题在于每次调用.Select会取消之前选中的对象,最终只有最后一个文本框被选中。要批量选中新创建的文本框并分组,有两种实用方案:
方法一:记录创建的Shape对象,构建ShapeRange统一处理
直接在创建文本框时把对象存入数组,最后用数组构建ShapeRange,即可一次性选中并分组:
Sub CreateShapesAndGroup() Dim sOrd As String Dim n As Integer Const iBr = 67 Dim shp As Shape Dim shpArray() As Shape sOrd = Selection.Text If Len(sOrd) = 0 Then Exit Sub ' 避免空文本导致错误 ReDim shpArray(1 To Len(sOrd)) For n = 1 To Len(sOrd) ' 创建文本框并赋值给变量 Set shp = ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, _ 50 + iBr * n, 150, 200, 70) shp.TextFrame2.TextRange.Characters.Text = Mid(sOrd, n, 1) ' 将当前文本框存入数组 Set shpArray(n) = shp Next n ' 用数组构建ShapeRange并操作 With ActiveSheet.Shapes.Range(shpArray) .Select ' 选中所有新创建的文本框 .Group ' 直接分组(无需选中也可执行此步骤) End With End Sub
方法二:通过统一名称前缀筛选选中
给每个新创建的文本框设置带统一前缀的名称,后续通过名称数组构建ShapeRange:
Sub CreateShapesWithNameAndGroup() Dim sOrd As String Dim n As Integer Const iBr = 67 Dim shp As Shape Dim shpNames() As String sOrd = Selection.Text If Len(sOrd) = 0 Then Exit Sub ReDim shpNames(1 To Len(sOrd)) For n = 1 To Len(sOrd) Set shp = ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, _ 50 + iBr * n, 150, 200, 70) ' 设置统一前缀的名称 shp.Name = "CustomTextBox_" & n shp.TextFrame2.TextRange.Characters.Text = Mid(sOrd, n, 1) shpNames(n) = shp.Name Next n ' 通过名称数组选中并分组 With ActiveSheet.Shapes.Range(shpNames) .Select .Group End With End Sub
重要提示
- 尽量避免频繁使用
Select:直接操作Shape对象比依赖Selection更高效,也能减少运行时错误。 - 如果不需要手动选中,直接调用
.Group即可完成分组,无需执行选中步骤。
内容的提问来源于stack exchange,提问作者Steinar Smith
相关产品推荐
相关产品推荐

