Sub Export_to_Word()
Const wdCollapseEnd = 0
Dim wdapp As Object, wddoc As Object
Dim newdoc As Boolean
On Error Resume Next
Sheet1.Range("A1:H20").Copy
Set wdapp = GetObject(, "word.Application")
If Err.Number Then
Err.Clear
Set wdapp = CreateObject("Word.Application")
End If
wdapp.Visible = True
Set wddoc = wdapp.documents("doc1.docx")
If Err.Number Then
Err.Clear
Set wddoc = wdapp.documents.Open(ThisWorkbook.Path & "\doc1.docx")
If Err.Number Then
Err.Clear
Set wddoc = wdapp.documents.Add
wddoc.SaveAs2 ThisWorkbook.Path & "\doc1.docx"
newdoc = True
End If
End If
wddoc.Active
If Not newdoc Then
wddoc.Content.Select
With wdapp.Selection
.Collapse wdCollapseEnd
.InsertNewPage
End With
End If
wdapp.Selection.PasteSpecial xlPasteValues
Set wddoc = Nothing
Set wdapp = Nothing
Application.CutCopyMode = False
MsgBox "Done!"
End Sub
Thử kiểm tra kỹ code sau.
Lần chạy đầu codesẽ tạo tập tin "doc1.docx" trong cùng thư mục với tập tin Excel. Tên và vị trí của tập tin DOCX tự thay đổi cho phù hợp.
Mã:Sub Export_to_Word() Const wdCollapseEnd = 0 Dim wdapp As Object, wddoc As Object Dim newdoc As Boolean On Error Resume Next Sheet1.Range("A1:H20").Copy Set wdapp = GetObject(, "word.Application") If Err.Number Then Err.Clear Set wdapp = CreateObject("Word.Application") End If wdapp.Visible = True Set wddoc = wdapp.documents("doc1.docx") If Err.Number Then Err.Clear Set wddoc = wdapp.documents.Open(ThisWorkbook.Path & "\doc1.docx") If Err.Number Then Err.Clear Set wddoc = wdapp.documents.Add wddoc.SaveAs2 ThisWorkbook.Path & "\doc1.docx" newdoc = True End If End If wddoc.Active If Not newdoc Then wddoc.Content.Select With wdapp.Selection .Collapse wdCollapseEnd .InsertNewPage End With End If wdapp.Selection.PasteSpecial xlPasteValues Set wddoc = Nothing Set wdapp = Nothing Application.CutCopyMode = False MsgBox "Done!" End Sub