2017-08-29 91 views
0

嗨我想從excel表格複製單元格並填充word文檔。我想將文本從excel單元格複製到Word文檔中的特定位置。我能夠將excel單元格中的文本存儲在一個字符串中,但不知道如何將它存儲在我在單詞doc中提到的單詞佔位符或書籤中。這是我到目前爲止有:如何從word vba添加文本到佔位符

Set ws = xlBook.Worksheets("DIP Main") 
    Tmp = ws.Cells(25, "C").Value 
    .Text = Tmp 
    .Execute Replace:=("Placeholder1") 
    ' [Placeholder1] = Tmp.Text 
    ' MyDOc.Fields("Placeholder1") = Tmp.Valu 

Ë

TMP從Excel中存儲的價值,但我不能夠取代的,並打印在佔位符我的word文檔,或是否有任何另一種在Word文檔的特定位置打印Tmp字符串的方式也可以。此外,即時通訊不在我的代碼中聲明任何佔位符,我不知道我是否應該。我在word文檔中創建了名爲「Placeholder1」的佔位符。我使用VBA單詞來編碼它。

對於全部代碼,請參閱本:How to copy excel range from a sheet and place it into a specific place it into a specific place in word using word vba

回答

0

這是Word中的書籤

ActiveDocument.Bookmarks("Placeholder1").Range = "abc123" 
+0

我將如何使它等於存儲在字符串中的值? –

0

插入文本這應該可以幫助你的方式代碼。

Sub ExcelToWord() 

    ' define all Excel variables you are going to use: 
    Dim Wb As Workbook 
    Dim Ws As Worksheet 
    Dim Cell As Range 

    ' define all Word variables you are going to use: 
     ' since you are running the code from Excel 
     ' you must specify "Word" for each data type 
    Dim WdApp As Word.Application 
    Dim Doc As Word.Document 

    ' define variables which you can use in either application: 
     ' (if you aren't sure, define separate ones) 
    Dim Tmp As String 
    Dim R As Long 
    Dim i As Integer 

    ' replace this name with the name & path of your own Word document 
    Tmp = "E:\PVT Archive\Class 1\1-2017 (Jan 2019)\STO 170317.docm" 
    If Dir(Tmp) = "" Then       ' Check if the file exists 
     MsgBox "The file doesn't exist.", _ 
       vbInformation, "Invalid file or path name" 
     Exit Sub 
    End If 
    Set WdApp = CreateObject("Word.Application") ' open Word 
    WdApp.Visible = True 
    Set Doc = WdApp.Documents.Open(Tmp)    ' open the document 

    If Not Doc.Bookmarks.Exists("Amark") Then 
     MsgBox "The bookmark 'Amark' doesn't exist.", _ 
       vbInformation, "Can't find bookmark" 
     Exit Sub 
    End If 

    Set Wb = ActiveWorkbook 
    Set Ws = Wb.Worksheets("DIP Main") 
    Tmp = Ws.Cells(25, "C").Value 

    Doc.Bookmarks("Amark").Range.Text = Tmp 
End Sub 

請注意,書籤將被替換爲下一個。此後不存在。如果你想重新使用它,你必須使用代碼重新設置它。