我在 word 中添加了宏,將 excel 中收集的注釋(例如,請參閱下面的 doc 和 excel 引文)添加到 word 檔案中的匹配單詞。我只想將這些評論添加到文本的選定部分,而不是整個檔案(在下面的示例中,選定的將是前 4 行文本,因此宏應將評論“請致電 1111111”添加到“issue1”并評論“請致電 2222222”到“issue2”,但在第 6 行中留下第二次出現的“issue1”而沒有評論,因為這不在選擇中。有什么想法如何解決這個問題?
word檔案,例如:
1個字issue1字字字字
2字逐字逐字字
3word字字字issue2字
4word字逐字逐字
5word字逐字逐字
6word字issue1字字字
7word字字issue3逐字逐句
excel表格,文本添加為??注釋(2列):
"issue1" "請撥打1111111"
" issue2" "請撥打2222222"
"issue3" "請撥打3333333"
我的宏現在從選定部分(檔案的前 4 行)中查找單詞,但在整個文本中添加注釋,直到檔案末尾,這意味著還向第 6 行中出現的未選中的“issue1”添加注釋。
Sub InsertCommentFromExcel()
Dim objExcel As Object
Dim ExWb As Object
Dim strWorkBook As String
Dim i As Long
Dim lastRow As Long
Dim oRng As range
Dim sComment As String
strWorkBook = "C:\Document\excelWITHcomments.xlsx"
Set objExcel = CreateObject("Excel.Application")
Set ExWb = objExcel.Workbooks.Open(strWorkBook)
lastRow = ExWb.Sheets("Words").range("A" & ExWb.Sheets("Words").Rows.Count).End(-4162).Row
For i = 1 To lastRow
Set oRng = Selection.Range
Do While oRng.Find.Execute(ExWb.Sheets("Words").Cells(i, 1)) = True
sComment = ExWb.Sheets("Words").Cells(i, 2)
oRng.Comments.Add oRng, sComment
Loop
Next
ExWb.Close
lbl_Exit:
Set ExWb = Nothing
Set objExcel = Nothing
Set oRng = Nothing
Exit Sub
End Sub
uj5u.com熱心網友回復:
lastPosition保存選擇的結尾。在每個之后,Find.Execute檢查找到的范圍的開始是否在保存的之前lastPosition。如果它已經落后lastPosition于查找回圈停止。
Sub InsertCommentFromExcel()
Dim objExcel As Object
Dim ExWb As Object
Dim strWorkBook As String
Dim i As Long
Dim lastRow As Long
Dim oRng As Range
Dim sComment As String
strWorkBook = "C:\Document\excelWITHcomments.xlsx"
Set objExcel = CreateObject("Excel.Application")
Set ExWb = objExcel.Workbooks.Open(strWorkBook)
lastRow = ExWb.Sheets("Words").Range("A" & ExWb.Sheets("Words").Rows.Count).End(-4162).Row
Set oRng = Selection.Range
Dim firstPosition As Long, lastPosition As Long
firstPosition = oRng.Start
lastPosition = oRng.End
For i = 1 To lastRow
Do While oRng.Find.Execute(ExWb.Sheets("Words").Cells(i, 1)) = True
If oRng.Start > lastPosition Then Exit Do
sComment = ExWb.Sheets("Words").Cells(i, 2)
oRng.Comments.Add oRng, sComment
Loop
Set oRng = ActiveDocument.Range(firstPosition, lastPosition)
Next
ExWb.Close
lbl_Exit:
Set ExWb = Nothing
Set objExcel = Nothing
Set oRng = Nothing
Exit Sub
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338010.html
