我知道,我看過這個鏈接:Word 2016-VBA- 如何在表格中選定的行下方插入行? 但是,不幸的是,即使它可能是微不足道的,我也不明白該怎么做。
這是我想要做的:1)在表的末尾添加行(來自 docSource)(第一部分運行良好)或 2)在所選行上方添加行(來自 docSource)(在 docTarget 上選擇的行)(第二部分努力尋找正確的方法)。
Dim docTarget As Document
Dim docSource As Document
Set docTarget = ActiveDocument
Set docSource = Documents.Open(strFileName)
IF SOMETHING THEN
'1) Working code
Dim myRange As Object
Set myRange = docTarget.Content
myRange.Collapse Direction:=wdCollapseEnd
myRange.FormattedText = docSource.Tables(2).Range.FormattedText
ELSE
'2) Can't figure it out
Dim myRange2 As Object
Set myRange2 = docTarget.Content
myRange2.Select 'What? - the row I already highlighted -
Selection.InsertRowsBelow
myRange2.FormattedText = docSource.Tables(2).Range.FormattedText
ENDIF
docSource.Close (0)
Set docSource = Nothing
Set docTarget = Nothing
有關資訊,我的 docSource 或 docTarget 表有 3 列,沒有合并單元格。
我歡迎任何想法或提示。
謝謝。
uj5u.com熱心網友回復:
我想我找到了答案,感謝 Timothy Rylatt 的耐心。但是,如果您有任何積極的批評或改進(更好的編碼),請不要猶豫,發表評論。
首先,在打開我的用戶表單之前,我得到了這個:
mySelectedRow = Selection.Information(wdEndOfRangeRowNumber)
mySlectedRow 宣告為 Public
其次,在用戶表單中,我得到了這個:
Private Sub btnOK_Click()
Dim strFileName As String
strFileName = ActiveDocument.Path & "\something\" & cboFileOption.Text
' Open selected item as docSource and assign docTarget to this document
Dim docTarget As Document
Dim docSource As Document
Set docTarget = ActiveDocument
Set docSource = Documents.Open(strFileName)
' Fill docTarget with the content of docSource
Dim myRange As Object
Set myRange = docTarget.Content
If Me.optEndTable.Value = True Then
myRange.Collapse Direction:=wdCollapseEnd
myRange.FormattedText = docSource.Tables(2).Range.FormattedText
Else
docSource.Tables(2).Range.FormattedText.Copy
docTarget.Content.Tables(1).Rows(mySelectedRow).Select
Selection.Rows(Selection.Rows.Count).Range.Paste
End If
' Close selected item (docSource) without saving
docSource.Close (0)
Set docSource = Nothing
Set docTarget = Nothing
' End
Me.Hide
End Sub
希望這是有道理的。謝謝
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/369563.html
