如何将光标定位至Word表格后的新行?VBA代码优化需求
解决光标定位至Word表格后新行的问题
原VBA代码执行完毕后,光标会停留在表格的(1,1)单元格开头,只需在表格操作逻辑结束后添加几行代码,即可将光标定位到表格后方的新行位置。
修改后的完整代码
Sub test_table() Dim objWord Dim objDoc Dim objSelection Dim i As Integer Dim j As Integer Set objWord = CreateObject("Word.Application") Set objDoc = objWord.Documents.Add Set objSelection = objWord.Selection objWord.Visible = True objWord.Activate objSelection.Font.Size = 12 objSelection.Font.Name = "Arial" objSelection.Font.Color = RGB(0, 0, 0) objSelection.TypeText "Accordingly, the " & vbLf Set country_table = objDoc.Tables.Add(objSelection.Range, 4, 5) With country_table With .Borders .enable = True .outsidecolor = RGB(0, 0, 0) .insidecolor = RGB(0, 0, 0) End With .Rows(1).shading.backgroundpatterncolor = RGB(230, 230, 230) .cell(1, 1).Range.InsertAfter "Part Number" .cell(1, 2).Range.InsertAfter "Item Description" .cell(1, 3).Range.InsertAfter "% of change in MRP" .cell(1, 4).Range.InsertAfter "% of change in offered rate" .cell(1, 5).Range.InsertAfter "Discount" For i = 1 To 3 .cell(i + 1, 1).Range.InsertAfter ThisWorkbook.Sheets("Overview").Cells(12 + i, 1).Text .cell(i + 1, 2).Range.InsertAfter ThisWorkbook.Sheets("Overview").Cells(12 + i, 2).Text & ThisWorkbook.Sheets("Overview").Cells(12 + i, 4).Text If IsError(ThisWorkbook.Sheets("Negotiation").Cells(16, (5 * i) - 2).Value) Then If ThisWorkbook.Sheets("Negotiation").Cells(16, (5 * i) - 2).Value = CVErr(xlErrDiv0) Then .cell(i + 1, 3).Range.InsertAfter "NA" End If Else .cell(i + 1, 3).Range.InsertAfter ThisWorkbook.Sheets("Negotiation").Cells(16, (5 * i) - 2).Text End If If IsError(ThisWorkbook.Sheets("Negotiation").Cells(17, (5 * i) - 2).Value) Then If ThisWorkbook.Sheets("Negotiation").Cells(17, (5 * i) - 2).Value = CVErr(xlErrDiv0) Then .cell(i + 1, 4).Range.InsertAfter "NA" End If Else .cell(i + 1, 4).Range.InsertAfter ThisWorkbook.Sheets("Negotiation").Cells(17, (5 * i) - 2).Text End If .cell(i + 1, 5).Range.InsertAfter ThisWorkbook.Sheets("Negotiation").Cells(18, (5 * i) - 2).Text Next i End With ' 核心修正代码:将光标移至表格后方的新行 country_table.Range.Select objWord.Selection.MoveRight Unit:=1, Count:=1 ' 用数值1替代Word常量wdCharacter,避免未引用库报错 objWord.Selection.TypeParagraph ' 插入新段落,光标自动定位到新行开头 End Sub
关键逻辑说明
country_table.Range.Select:选中整个表格的内容范围,确保光标起点在表格区域内objWord.Selection.MoveRight Unit:=1, Count:=1:将光标向右移动一个字符,跳出表格边界objWord.Selection.TypeParagraph:插入新段落,此时光标会自动定位到表格后方的新行开头
内容的提问来源于stack exchange,提问作者JOSHY T R
相关产品推荐
相关产品推荐

