简体   繁体   中英

Creating Word document from Excel through VBA

Folks. I have an Excel file and want to create a Word document with the data in a sheet. The program shows an error and I can't find the reason.

I tried to use the following code:

Private Sub CommandButton1_Click()
' Objetos Word
  Dim obj1 As New Application
  Dim wdDoc As Word.Document

' Objetos Excel
  Dim wbBook As Workbook
  Dim wsSheet As Worksheet

  Dim Caminho, Arquivo, Nome_aluno, Ender As String
  Dim Gen_p, Gen_a, Hora, Prof, Resp As String
  Dim i, Comp As Integer
  Dim Coord_C As Integer
  Dim Coord_L As Integer
  Caminho = "D:\Data\Office\Excel\"
  Arquivo = "Anexo D - Ata de defesa TCC.docx"

The code continues, but is irrelevant for now. The point is when I run the code I get the message:

User defined type not defined

This is weird, because in another Excel file I can run it, and it works fine. What have I missed? Do I have to link something?

To create a new Word doc from another application, add this...

Dim appWD As Word.Application 

Set appWD = CreateObject("Word.Application") 
appWD.Documents.Add

https://docs.microsoft.com/en-us/office/vba/excel/concepts/working-with-other-applications/controlling-one-microsoft-office-application-from-another

since your code uses:

Dim obj1 As New Application

You must set a VBA reference to whatever application (Word?) obj1 relates to. That is done via Tools|References. You must also tell VBA what application that is. For example:

Dim obj1 As New Word.Application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM