當前位置:成語大全網 - 新華字典 - VBA中 可否實現 讓txt中的文檔內容,替換到word的標簽中去

VBA中 可否實現 讓txt中的文檔內容,替換到word的標簽中去

下面是代碼是我應用中的壹個過程,可以作為例子供妳參考:

'★★★★自動生成提示書文件★★★★

Sub?生成提示書WORD文件()

'變量定義

Dim?i,?j,?h,?p,?n,?st

Set?st?=?GetSheet("提示書用表")

If?st?Is?Nothing?Then?Exit?Sub

st.Activate

h?=?9?'標題行

n?=?Trim(st.Cells(3,?2).Value)

If?Not?FileExist(n)?Then

MsgBox?"模板文件("?&?n?&?")不存在!"

Exit?Sub

End?If

p?=?InStrRev(n,?"\")

If?p?=?0?Then?p?=?""?Else?p?=?Left(n,?p)

Dim?WordApp?As?Object

'開始啟動WORD進程

Set?WordApp?=?CreateObject("Word.Application")

i?=?h?+?1

While?st.Cells(i,?1)?<>?""

WordApp.Documents.Add

WordApp.Selection.InsertFile?Filename:=n

For?j?=?1?To?st.UsedRange.Columns.Count

If?st.Cells(h,?j)?<>?""?Then

With?WordApp.Selection.Find

.Text?=?"<<"?&?st.Cells(h,?j)?&?">>"

.Replacement.Text?=?st.Cells(i,?j).Text

.Forward?=?True

.Format?=?False

.MatchCase?=?False

.MatchWholeWord?=?False

.MatchByte?=?True

.MatchWildcards?=?False

.MatchSoundsLike?=?False

.MatchAllWordForms?=?False

.Wrap?=?1?'wdFindContinue

.Execute?Replace:=2?'wdReplaceAll

End?With

End?If

Next?j

WordApp.ActiveDocument.SaveAs?Filename:=p?&?st.Cells(i,?1).Text?&?".doc",?FileFormat:=0?'wdFormatDocument

WordApp.ActiveDocument.Close

i?=?i?+?1

Wend

WordApp.Quit?'退出

Set?WordApp?=?Nothing?'取消變量

MsgBox?"全部文件生成完畢("?&?p?&?")!"

End?Sub

此代碼是EXCEL中的VBA,打開壹個WORD模板文件,把裏面所有的標簽按表格內容進行替換,然後生成表格裏面指定的名字的文件。