我是 Word VBA 新手,正在尝试在 Word 文档的表格中插入值。
我面临的问题是,当我循环遍历表格时,它会在粘贴从 Excel 复制的值之前剪切文本。
感谢任何帮助
For i = 2 To 10
res = xlApp.VLookup(srch, xlWb.Worksheets("Sheet1").Range("AO:CR"), i, False)
Selection.TypeText Text:=" " & res
Selection.MoveRight Unit:=wdCell
'---------------------------------------------------
Next i
预期结果:循环遍历 Excel 并粘贴,继续将值放置在每个框中的书面文本后面,然后移至下一个框。
Sub AppendToCell()
' Check if the selection is in a table
If Selection.Information(wdWithInTable) Then
' Get the current cell
Dim currentCell As Cell, i As Long, res
For i = 2 To 10
Set currentCell = Selection.Cells(1)
res = xlApp.VLookup(srch, xlWb.Worksheets("Sheet1").Range("AO:CR"), i, False)
If Not VBA.IsError(res) Then
currentCell.Range.Text = currentCell.Range.Text & " " & res
Selection.Move wdCell, 1
End If
Next
Else
MsgBox "The selection is not in a table cell."
End If
End Sub