我正在研究轴承报告。我必须复制并从Excel文件中找到相关的方位数据并将其粘贴到单词表中。我已经计算出代码如何更新单词表?
要转到word文件中的相关位置,并在所需的word文档中粘贴一些数据。
Sub CreateNewWordDoc() Dim wrdApp As Word.Application Dim wrdDoc As Word.Document Dim i As Integer Dim arr(12) 'Bearing numbers I need to search arr(0) = "(249_L), 38,7 %" arr(1) = "(248_R), 38,7 %" arr(2) = "(249_M), 38,7 " arr(3) = "(3560), 38,7 " arr(4) = "(3550), 38,7 %" arr(5) = "(349_), 38,7 %" arr(6) = "(348_), 38,7 %" arr(7) = "(451), 38,7 %" arr(8) = "(450L), 38,7 " arr(9) = "(450R), 38,7 " arr(10) = "(151), 38,7 %" arr(11) = "(150L), 38,7 %" arr(12) = "(150R), 38,7 %" Set wrdApp = CreateObject("Word.Application") wrdApp.Visible = True 'location of my word document Set wrdDoc = wrdApp.Documents.Open("E:\ShareDrive_Ruehl\full-flexible-MBS-models_report\example-report\FullFlexibleGearbox - Copy (2).docx") wrdDoc.Activate wrdApp.Selection.HomeKey unit:=wdStory 'for loop to reach all bearing location For i = 0 To 12 With wrdApp.Selection With .Find .ClearFormatting .MatchWildcards = False .MatchWholeWord = False .Text = arr(i) .Execute End With ' Here is where I need to paste my copied data. .InsertAfter "I can just paste this shit" .HomeKey unit:=wdStory End With Next End Sub
转到Excel文件中的位置,找到相关的数据,并复制相关的数据,这里是该代码。
Sub CopyToWord() 'Copy the range Which you want to paste in a New Word Document Cells.Find(What:=arr(0), After:=ActiveCell, LookIn:=xlFormulas _ , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Activate ActiveCell.Offset(2, 0).Range("A1:g8").Select Selection.Copy End Sub
我已经写了两个从Excel中VBA运行这些代码。但现在我必须将第二个代码中的复制数据粘贴到位于第一个代码中的表格中(该位置的位置不是在我找到该单词的位置之后)要去那个位置,我知道代码,可以通过下面给出的图片更好地理解)。
这是我选择单词中我需要替换的数据的代码。我需要写的字相似,替代与复制的数据
Sub pasting()
Dim sSample, rResult As String
sSample = "(450R), 38,7 % "
Set rRange = ActiveDocument.Content
Selection.Find.Execute FindText:=sSample, _
Forward:=True, Wrap:=wdFindStop
Selection.MoveDown unit:=wdLine, Count:=1
Selection.EndKey unit:=wdLine
Selection.MoveRight unit:=wdCharacter, Count:=1
Selection.EndKey unit:=wdLine
Selection.MoveDown unit:=wdLine, Count:=1
Selection.MoveDown unit:=wdLine, Count:=5, Extend:=wdExtend
Selection.MoveLeft unit:=wdCharacter, Count:=5, Extend:=wdExtend
Selection.PasteAndFormat (wdPasteDefault)
End Sub
不幸的是,虽然我抄什么,我想我不能够在解决办法的数据。我不知道如何在现有表格中粘贴数据。
这幅图解释得更好。我需要在excel中搜索轴承248_R的数据并粘贴到word中。 这是Word文件
这是Excel文件
为什么不用你(而不是这个广泛的VBA脚本)链接/嵌入你的Excel数据,如[在Word文档中嵌入Excel工作表](http://www.excel-easy.com /examples/embed.html)或[将Excel数据链接到Word文档](http://www.k2e.com/tech-update/tips/158-linking-excel-data-into-word-documents)?这会比使用脚本容易得多,并且会自动更新Word中的数据。不要重新发明轮子! –
Peh的建议看起来颇具吸引力。但是,如果这不起作用,请注意您无法将Excel表格中的数据粘贴到现有的Word表格中。您必须将每个Excel单元格的内容写入每个现有的Word单元格。 – Variatus
感谢您的建议@Peh但我正在编写一个代码,如果我插入其他方位数据集,它必须自动更新。我的意思是,如果我把其他Excel表格相同的轴承名称,但不同的值,它必须自动更新 –