宏从Excel中的数据生成Word文档

时间:2019-05-31 17:49:11

标签: excel macros word wordpad

我想从Excel中特定列的数据生成Word文档... 这样我将在Excel中有N页的N页单词文档...

我还想自定义单词中该数据的位置.....

例如, 说excel的第一个数据应该出现在word文档的第一页上,距顶部10cm,距左侧5cm。

我尝试了一个宏,它使用来自excel特定单元格的数据生成一个单词。

但是无法在新页面上找到下一个单元格数据并自定义其位置。

Option Explicit

Sub Create_New_WordDoc()
Dim wsApp As Word.Application

Set wsApp = CreateObject("Word.Application")
With wsApp
        .Visible = True
        .Documents.Add
End With

Set wsApp = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

您可以使用关键文本创建单词“ template”来查找和替换。这是excel中的宏,您的单词doc中将包含<<和>>之间的文本,并且您将进行搜索和替换

Sub Button5_Click()

Dim wApp As Word.Application
Dim wDoc As Word.Document
Set wApp = CreateObject("Word.Application")
FNameQ = Range("E24").Value
Dim FnameP As String
FnameP = " C OF C"
Dim FName As String
FName = FNameQ & FnameP
wApp.Visible = True

Set wDoc = wApp.Documents.Open("LOCATION OF FILE\XXXX.doc")

With wDoc
    .Application.Selection.Find.Text = "<<CUSTNAME>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E22")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<PONUM>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E23")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<PARTNUM>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E24")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<DRAWNUM>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E25")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<DRAWREV>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E26")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<PARTDESC>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E27")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<MATERIAL>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E28")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<SHIPDATE>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E29")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<NAME>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E31")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<TITLE>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E32")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<SHIPDATE>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E29")
    .Application.Selection.EndOf

    .SaveAs2 Filename:=FName, _
    FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False
End With



End Sub