Word表格ActiveX文本框内容一键导入Excel宏代码问题
Word表格ActiveX TextBox内容导入Excel的修复方案
当Word表格单元格替换为ActiveX TextBox控件后,原代码的CELLER.Range.Text无法读取控件内的内容——该属性仅针对单元格的原生文本,而非嵌入的控件对象。以下是两种可行的修改方式:
方式一:遍历单元格内嵌控件读取内容
通过遍历单元格的InlineShapes集合,筛选出ActiveX TextBox并读取其Text属性:
If CELLER.RowIndex = 2 And CELLER.ColumnIndex = 2 Then Dim shp As InlineShape Dim txtContent As String txtContent = "" For Each shp In CELLER.Range.InlineShapes ' 匹配Forms.TextBox.1类型的ActiveX控件 If shp.OLEFormat.ProgID = "Forms.TextBox.1" Then txtContent = shp.OLEFormat.Object.Text Exit For ' 找到目标控件后终止遍历 End If Next shp ' 保持原有的文本清理逻辑 Sheet2.Cells(LL, COL_EQUIP).Value2 = Application.Trim(Replace(Replace(txtContent, Chr(13), vbNullString), Chr(7), vbNullString)) End If
方式二:通过控件名称直接定位(推荐)
若你给TextBox设置了固定名称(比如tb_Equipment),可以直接通过名称快速访问,避免遍历:
If CELLER.RowIndex = 2 And CELLER.ColumnIndex = 2 Then Dim targetTB As Object Dim txtContent As String ' 尝试通过名称获取控件 On Error Resume Next Set targetTB = CELLER.Range.Parent.Shapes("tb_Equipment").OLEFormat.Object On Error GoTo 0 ' 优先读取控件内容,无控件则 fallback到单元格原生文本 If Not targetTB Is Nothing Then txtContent = targetTB.Text Else txtContent = CELLER.Range.Text End If Sheet2.Cells(LL, COL_EQUIP).Value2 = Application.Trim(Replace(Replace(txtContent, Chr(13), vbNullString), Chr(7), vbNullString)) End If
关键说明
- ActiveX控件属于Word的
InlineShapes或Shapes集合,需通过OLEFormat.Object访问其原生属性。 - 若单元格内存在多个TextBox,方式一会读取第一个匹配的控件,需根据实际需求调整遍历逻辑。
- 确保Word宏安全设置允许访问ActiveX控件,否则会触发权限错误。
内容的提问来源于stack exchange,提问作者Goh Chun Wei
相关产品推荐
相关产品推荐

