使用VBA在Word中退出表格时遇到问题
解决Word宏中退出表格后输入文本的问题
问题核心:你的光标停留在表格最后一个单元格内,直接执行TypeParagraph只会在单元格内创建新段落,无法跳出表格。之前尝试的代码未生效是因为未正确定义表格对象,且未确保光标移动到表格外部的正确位置。
修复方案
在输入paragraph 3前,添加代码将光标定位到表格的外部末尾,替换你原有的.TypeParagraph和.TypeText部分:
' 将光标移动到表格范围的末尾 .Tables(1).Range.Collapse wdCollapseEnd ' 后移一位确保完全脱离表格区域 .MoveRight Unit:=wdCharacter, Count:=1 .TypeParagraph .TypeText Text:="paragraph 3"
修改后的完整代码
Sub Macro2() With Selection .TypeText Text:="paragraph 1" .TypeParagraph .TypeText Text:="paragraph 2" .TypeParagraph ActiveDocument.Tables.Add Range:=.Range, NumRows:=4, NumColumns:= _ 2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _ wdAutoFitFixed With .Tables(1).Range For x = 1 To 8 .Cells(x).Width = 180 Next End With ' .Tables(1).Borders.Enable = False CellFormat .TypeText Text:="Sundance Senior Services" .MoveRight Unit:=wdCell CellFormat .TypeText Text:="Bella Pregnancy Center" .MoveRight Unit:=wdCell CellFormat .TypeText Text:="Compassion International" .MoveRight Unit:=wdCell CellFormat .TypeText Text:="Far Reaching Ministries" .MoveRight Unit:=wdCell CellFormat .TypeText Text:="The Ram Center" .MoveRight Unit:=wdCell CellFormat .TypeText Text:="Jail/Prison Ministries" .MoveRight Unit:=wdCell CellFormat .TypeText Text:="Funeral Services" ' --- 修复部分开始 --- .Tables(1).Range.Collapse wdCollapseEnd .MoveRight Unit:=wdCharacter, Count:=1 .TypeParagraph .TypeText Text:="paragraph 3" ' --- 修复部分结束 --- End With End Sub Sub CellFormat() ListGalleries(wdBulletGallery).ListTemplates(1).Name = "" Selection.Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _ ListGalleries(wdBulletGallery).ListTemplates(1), ContinuePreviousList:= _ False, ApplyTo:=wdListApplyToWholeList, DefaultListBehavior:= _ wdWord10ListBehavior End Sub
关键说明
Tables(1).Range.Collapse wdCollapseEnd:将光标定位到表格范围的末尾(对应表格结束标记的位置).MoveRight Unit:=wdCharacter, Count:=1:将光标从表格结束标记后移一位,彻底脱离表格区域,此时执行TypeParagraph会在表格下方创建独立的新段落
内容的提问来源于stack exchange,提问作者WinginSue
相关产品推荐
相关产品推荐

