Option Explicit
Sub Button1_Click()
Dim lastRow As Long, r As Long, filename As String, filenames(), fso As Object
With ThisWorkbook.Worksheets("word_files")
lastRow = .Cells(Rows.Count, "A").End(xlUp).Row
' lay du them 1 dong sau dong co du lieu cuoi cung
filenames = .Range("A1:A" & lastRow + 1).Value
End With
Set fso = CreateObject("Scripting.FileSystemObject")
' bo dong lay them cuoi cung, chi xet cac dong con lai
For r = 1 To UBound(filenames) - 1
filename = ThisWorkbook.Path & "\" & filenames(r, 1)
' neu tap tin ton tai thi thuc hien
If fso.FileExists(filename) Then FindAndReplace filename, ThisWorkbook.Worksheets("data")
Next r
Set fso = Nothing
End Sub
Private Sub FindAndReplace(ByVal filename As String, ByVal sh As Worksheet)
Const wdReplaceAll = 2
Const wdFindContinue = 1
Dim num_of_cust As Long, num_of_column As Long, i As Long, j As Long, new_filename As String
Dim template As Object, t As Object
' cot cuoi cung co du lieu. Tieu de cac cot tai dong 1 cua sheet
num_of_column = sh.Cells(1, Columns.Count).End(xlToLeft).Column
' dong cuoi cung co du lieu o cot A
num_of_cust = sh.Cells(Rows.Count, "A").End(xlUp).Row - 1
With CreateObject("word.application") ' late binding
.Visible = True
For i = 1 To num_of_cust
' mo tap tin filename cho tung Ho Ten
Set template = .documents.Open(filename)
Set t = .Selection
With t.Find
.ClearFormatting
.Replacement.ClearFormatting
.Forward = True
.Wrap = wdFindContinue
' ^c co nghia la text thay the lay tu Clipboard
.Replacement.text = "^c"
End With
For j = 1 To num_of_column
With t.Find
' text can thay the - text can tin
.text = sh.Cells(1, j).Value
' sao chep text thay the vao Clipboard
CopyTextToClipboard sh.Cells(i + 1, j).Value
' thay the tat ca cac doan duoc tim thay. Text thay the lay tu Clipboard
.Execute Replace:=wdReplaceAll
End With
Next j
new_filename = Left(filename, InStrRev(filename, ".") - 1) & "_" & i & "-don_xin.docx"
' luu lai voi ten moi
template.SaveAs new_filename
' dong tap tin hien hanh
template.Close
Next
.Quit
End With
Set t = Nothing
Set template = Nothing
End Sub
Private Sub CopyTextToClipboard(ByVal text As String)
With CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.SetText text
.PutInClipboard
End With
End Sub