Here’s an example of VBA code that writes data to a Word document:
Sub WriteDataToWord() Dim wrdApp As Object ' Word.Application Dim wrdDoc As Object ' Word.Document Dim data As String ' Create a new instance of Word Set wrdApp = CreateObject("Word.Application") ' Disable the Word application visibility for faster processing wrdApp.Visible = False ' Create a new document Set wrdDoc = wrdApp.Documents.Add ' Specify the data to be written to the document data = "Hello, World!" ' Replace with your data ' Write data to the document wrdDoc.Content.Text = data ' Save the document wrdDoc.SaveAs "C:\Path\to\your\Document.docx" ' Replace with the path and filename of your Word document ' Close the document wrdDoc.Close ' Quit Word wrdApp.Quit ' Clean up the objects Set wrdDoc = Nothing Set wrdApp = Nothing End Sub
In this code, you need to modify the data
variable to contain the data you want to write to the Word document. The example provided writes the string “Hello, World!” to the document.
You also need to replace "C:\Path\to\your\Document.docx"
with the actual path and filename where you want to save the Word document.
When you run this code, it will create a new instance of Word, create a new document, write the data to the document’s content, save the document to the specified path and filename, close the document, quit Word, and clean up the objects.
Note: Make sure that you have the necessary permissions to create and modify files in the specified path.