Excel

VBA

by Andrea Spera

Automazione di Microsoft Word con VBA
Questo script VBA permette di aprire un documento di Word direttamente da Excel, utilizzando l'automazione di Microsoft Word tramite la libreria di oggetti di Word. Nel codice, viene aperto un file Word esistente, viene aggiunto del testo e una tabella, e il documento viene salvato con un nuovo nome. Questa tecnica รจ utile per automatizzare la generazione e modifica di documenti Word a partire da dati presenti in altre applicazioni, come Excel.
Codice
Sub open_doc_word()
'Reference to Microsoft Word Object Library
Dim myApp As Word.Application
Dim myDoc As Word.Document
Dim myFile As String
Dim myParagraph As Word.Paragraph
Dim myTable As Word.Table
    'file to be opened
    myFile = ThisWorkbook.Path & "\test.docx"
    Set myApp = CreateObject("Word.Application")
    Set myDoc = myApp.Documents.Open(myFile)
    
    myApp.Visible = True
    
    Set myParagraph = myDoc.Content.Paragraphs.Add(myDoc.Bookmarks("\StartOfDoc").Range)
    'https://learn.microsoft.com/en-us/office/vba/word/concepts/miscellaneous/predefined-bookmarks
    'add some text
    myParagraph.Range.Text = "Some text..."
    
    'insert a table
    Set myTable = myDoc.Tables.Add(myDoc.Bookmarks("\EndOfDoc").Range, 2, 2) '2 rows and 32 columns
        myTable.Range.ParagraphFormat.SpaceAfter = 0
        myTable.Range.ParagraphFormat.SpaceBefore = 0
        myTable.Borders.Enable = True
        myTable.Cell(1, 1).Range.Text = "Something..."
        myTable.Cell(1, 2).Range.Text = "Something else..."
        myTable.Columns(1).Width = myApp.CentimetersToPoints(5)
        myTable.Columns(2).Width = myApp.CentimetersToPoints(10)
    
    'save with new name
    myDoc.SaveAs2 Filename:=myFileName & "new_doc.docx", FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False
End Sub