我有一些代碼,做這樣的事情。在Word中,我不是使用書籤來替換字段,而是使用特殊標記(如<<NAME>>
)。
您可能需要適應。我使用ListObject(新的Excel「表格」),如果您使用簡單的範圍,則可以更改它。
創建一個「Template.docx」文檔,使其成爲只讀文件,並在其中放置可替換字段(<<NAME>>
等)。一個簡單的docx會做,它不一定是一個真正的模板(dotx)。
Public Sub WriteToTemplate()
Const colNum = 1
Const colName = 2
Const colField2 = 3
Const cBasePath = "c:\SomeDir"
Dim wordDoc As Object, sFile As String, Name As String
Dim lo As ListObject, theRow As ListRow
Dim item As tItem
Set lo = ActiveCell.ListObject
Set theRow = ActiveCell.ListObject.ListRows(ActiveCell.Row - lo.Range.Row)
With theRow.Range
'I use one of the columns for the filename:
Debug.Print "writing " & theRow.Range.Cells(1, colName).text
'A filename cannot contain any of the following characters: \/: * ? " < > |
Name = Replace(.Cells(1, colName), "?", "")
Name = Replace(Name, "*", "")
Name = Replace(Name, "/", "-")
Name = Replace(Name, ":", ";")
Name = Replace(Name, """", "'")
sFile = (cBasePath & "\" & Name) & ".docx"
Debug.Print sFile
Set wordApp = CreateObject("word.Application")
If Dir(sFile) <> "" Then 'file already exists
Set wordDoc = wordApp.Documents.Open(sFile)
wordApp.Visible = True
wordApp.Activate
Else 'new file
Set wordDoc = wordApp.Documents.Open(cBasePath & "\" & "Template.docx")
wordApp.Selection.Find.Execute Forward:=(wordApp.Selection.Start = 0), FindText:="««NUM»»", ReplaceWith:=.Cells(1, colNum)
wordApp.Selection.Collapse direction:=1 'wdCollapseEnd
wordApp.Selection.Find.Execute FindText:="««NAME»»", ReplaceWith:=.Cells(1, colName)
wordApp.Selection.Collapse direction:=1 'wdCollapseEnd
wordApp.Selection.Find.Execute FindText:="««FIELD2»»", ReplaceWith:=.Cells(1, colField2)
wordDoc.ListParagraphs.item(1).Range.Select
wordApp.Selection.Collapse direction:=1 'wdCollapseEnd
wordApp.Visible = True
wordApp.Activate
On Error Resume Next
'if this fails (missing directory, for example), file will be unsaved, and Word will ask for name.
wordDoc.SaveAs sFile 'Filename:=(cBasePath & "\" & .Cells(1, colName))
On Error GoTo 0
End If
End With
End Sub
這基本上覆制代碼中的郵件合併功能,給你更多的控制。
來源
2015-01-14 18:22:10
pgr
Mailmerge可以做到這一點。 – 2014-11-26 05:47:55
書籤和命名範圍是否都有相同(匹配)的名稱?舉個例子。你想運行它的所有書籤或所有命名的範圍?換句話說,什麼定義你的宏的範圍? – 2014-11-26 11:56:54
嗨KazJaw,感謝您的消息。是的,我已經爲書籤和命名單元使用了相同的名稱。例如,我的第一個書籤叫做Sample_1,我用它來命名我想從中導出數據的單元格。我有7個書籤,我希望傳輸數據,每個書籤都有一個同名的excel姐妹單元。 – 2014-11-27 12:08:28