Here’s an example of VBA code that reads data from a Word document:
Sub ReadDataFromWord() Dim wdApp As Object ' Word.Application Dim wdDoc As Object ' Word.Document Dim filePath As String Dim fileContent As String ' Specify the path and filename of the Word document filePath = "C:\Path\to\your\Document.docx" ' Create a new instance of Word application Set wdApp = CreateObject("Word.Application") ' Open the Word document Set wdDoc = wdApp.Documents.Open(filePath) ' Read the content of the Word document fileContent = wdDoc.Content.Text ' Close the Word document wdDoc.Close SaveChanges:=False ' Quit the Word application wdApp.Quit ' Display the document content in a message box MsgBox fileContent End Sub
In this code, you need to modify the filePath
variable to the actual path and filename of your Word document.
When you run this code, it will open the Word document specified by the filePath
, read its content using the Content.Text
property, store it in the fileContent
variable, close the document without saving changes, quit the Word application, and then display the document content in a message box.
Note: Make sure that the specified Word document exists in the specified path and is accessible by the VBA code.