Меню

Appword as word application ошибка библиотеки

 

SanMiguel

Пользователь

Сообщений: 3
Регистрация: 19.03.2020

Приветствую!

Макрос для выгрузки данных из Excel в Word. Проблема вот в чем:

Макрос прекрасно работает в версиях Excel 2016/2019. Но в Excel 2010 не может найти библиотеку Microsoft Word 16.0 Object Library – пишет MISSING. Если ручками убрать библиотеку 16.0 и поставить 14.0, то макрос запускается. Я как понял, нужно использовать позднее связывание, но куда его запилить ума не приложу.
Ругается на 3 строку (Public AppWord As Word.Application, iWord As Word.Document).
Буду признателен за помощь.

Код
Option Explicit
Option Private Module

Public AppWord As Word.Application, iWord As Word.Document



Sub CreateDoc()
Dim MyArray(), BasePath As String, iFolder As String, iTemplate As String
Dim tmpArray, tmpSTR As String, iRow As Long, iColl As Long, i As Long, j As Long, q As Long

Application.ScreenUpdating = 0
On Error GoTo iEnd

iFolder = Range("FILE_WORD").Value: If Right(iFolder, 1) <> "" Then iFolder = iFolder & ""
iTemplate = Range("FILE_TEMPLATE").Value: If Right(iTemplate, 1) = ";" Then iTemplate = Left(iTemplate, Len(iTemplate) - 1)
BasePath = ThisWorkbook.Path & "Result": Call FolderCreateDel(BasePath)

With Sheets("data")
    iRow = .UsedRange.Row + .UsedRange.Rows.Count - 1: iColl = .UsedRange.Column + .UsedRange.Columns.Count - 1
    MyArray = .Range(.Cells(1, 1), .Cells(iRow, iColl)).Value
End With

'создаем скрытый объект Word
Set AppWord = CreateObject("Word.Application"): AppWord.Visible = False

'перебираем массив
For i = 2 To iRow
    If MyArray(i, 1) = "ok" Then
    
        'перебираем указанные word-шаблоны
        tmpArray = Split(MyArray(i, 3), ";")
        For q = 0 To UBound(tmpArray)
            tmpSTR = iFolder & tmpArray(q) & ".docx"
            If Len(Dir(tmpSTR)) > 0 Then
                Set iWord = AppWord.Documents.Open(tmpSTR, ReadOnly:=True)
            
                'делаем замену переменных
                For j = 4 To iColl
                    Call ExportWord(MyArray(1, j), MyArray(i, j))
                Next j
                
                iWord.SaveAs Filename:=BasePath & MyArray(i, 2) & " - " & tmpArray(q) & ".docx", FileFormat:=wdFormatXMLDocument
                iWord.Close False: Set iWord = Nothing
            End If
            'tmpSTR = ""
        Next q
        'Erase tmpArray

    End If
Next i

AppWord.Quit: Set AppWord = Nothing
'Erase MyArray: BasePath = "": iFolder = "": iTemplate = ""

Application.ScreenUpdating = 1
MsgBox "Файлы сформированы.", vbInformation

Exit Sub

iEnd:
    AppWord.Quit: Set AppWord = Nothing
    'Erase MyArray: BasePath = "": iFolder = "": iTemplate = ""
    Application.ScreenUpdating = 1
    MsgBox "При обработке данных возникла ошибка.", vbCritical
End Sub

In spite of heavy googling, I am not able to figure out, what is wrong with this. Do I still miss a reference or something? If you can see, where the error lies, I’ll be forever grateful!

References:

  • Visual Basic For Applications
  • Microsoft Excel 16.0 Object Library
  • OLE Automation
  • Microsoft Office 16.0 Object Library
  • RefEdit Control
  • Microsoft Word 16.0 Object Library

Variables:

Public appWord As Word.Application
Public sapmWord As Word.Document

Dim asNimi As String 'in this current sub

Code:

On Error Resume Next

Set appWord = GetObject(, "Word.Application")
If Err <> 0 Then
    Set appWord = CreateObject("Word.Application")
End If
On Error GoTo 0
appWord.Visible = True
Set sapmWord = appWord.documents.Open("C:ThisIsWorkingandDocOpens.docx")
'sapmWord.Activate 'doesn't make a difference

With sapmWord
    Selection.EndKey Unit = wdStory 'this line is first line to give an error. With or without a dot in the beginning of line.
    Selection.TypeText Text:=asNimi 'this line too, if previous is commented
'...and so on!
End With

sapmWord.Close savechanges:=True
Set appWord = Nothing
Set sapmWord = Nothing

Cindy Meister's user avatar

asked Jun 26, 2018 at 7:54

lego tera's user avatar

10

sapmWord is a word document. A word document doesn’t have a selection method. The Word application object has it, so probably you mean (and yes, you need the ‘.’)

With appWord 
    .Selection.EndKey Unit:= wdStory 
    .Selection.TypeText Text:=asNimi 
    '...and so on!
End With

answered Jun 26, 2018 at 8:14

FunThomas's user avatar

FunThomasFunThomas

19k2 gold badges17 silver badges34 bronze badges

9

You have to change sapmWord.Close savechanges:=True for appWord.quit savechanges:=True

answered Jun 10, 2020 at 19:47

user13723313's user avatar

1

To use With, you must reference members with a .:

With sapmWord
    .Selection.EndKey Unit = wdStory
    .Selection.TypeText Text:=asNimi
End With

answered Jun 26, 2018 at 8:10

LS_ᴅᴇᴠ's user avatar

LS_ᴅᴇᴠLS_ᴅᴇᴠ

10.7k1 gold badge22 silver badges46 bronze badges

3

At the end I had no choice but adding bookmarks to the Word document and filling them with VBA. I still have no clue why those original codes did not work in my code, although they work for others. Thank you all for help, maybe some one else is getting answers here anyway.

answered Jun 27, 2018 at 11:08

lego tera's user avatar

  • Remove From My Forums
  • Question

  • I have an MS Access file that opens a word template, populates it with data and saves it to a local share. The following code produces the above error:

    Dim WordObj As Word.Application
        
      Set WordObj = CreateObject("Word.Application")
      WordObj.Visible = True
      WordObj.Activate
      WordObj.ShowMe
      WordObj.WindowState = wdWindowStateMaximize
      WordObj.Documents.Add(GetTemplatePath(strDocPath))
    
    WordObj.ActiveDocument.SaveAs FileName:=FullDocName, FileFormat:=12 //this line produces the above error

    I have tried many combinations of early / late binding with the word application object and always get the same result. The word document will open and the functions which insert text will run successfully, but the document will not be saved and if any further
    editing is attempted Word will crash.

    I suspect that code isnt the problem; I have another identical workstation that is able to open and save the output document. What external factors could cause this?

Answers

  • What version of office do you have installed on your PC?

    You can specify the version of excel you are creating the object.

    From :

    Set WordObj = CreateObject(«Word.Application»)

    to :

    Set WordObj = CreateObject(«Word.Application.12»)

    You also may want to try using the following

    WordObj.ActiveDocument.SaveAs FileName:=FullDocName, FileFormat:=acFileFormatAccess2007

    Check the menu in access vba Tools — References Microsoft Word XX.X object Library.  You may have to browse for a newer version of the object library.  what sometimes hapPens if the macro was developed on a PC with 2003 the reference may be
    pointing to the object library 11.0 while you need 12.0.

    Make sure the version  of the object library is compatible with Word 2007.  Version 12 is office 2007.  The create object will automatically use the defualt version of office that is installed on your PC.  If you have  office 2010
    installed you may need to specify a differnt version.

    Errors like -2147417851 (80010105) are usually caused by not having the priveledge to open the file.  Make sure you can open the file by double clicking on the file and opening.  I would aslo suspect you would get the error if your configuration
    (like the reference) doesn’t support office 2007.


    jdweng

    • Marked as answer by

      Friday, February 25, 2011 9:50 AM

  • Wrong approach. You mix the application object with document object. Try this:

      Dim appWord As New Word.Application
      Dim objWord As Word.Document

      Set objWord = appWord.Documents.Add(GetTemplatePath(strDocPath))

      appWord.visible = True
      appWord.Activate
      appWord.ShowMe
      appWord.WindowState = wdWindowStateMaximize

      appWord.ActiveDocument.SaveAs FileName:=FullDocName, FileFormat:=12

    Greg

    • Marked as answer by
      Bruce Song
      Friday, February 25, 2011 9:50 AM

  • Hi Richard,

    it’s interesting because this cide works fine for me with Office 2007:

     Set wordobj = CreateObject("Word.Application")
     wordobj.Visible = True
     wordobj.Activate
     wordobj.ShowMe
     wordobj.WindowState = wdWindowStateMaximize
     wordobj.Documents.Add "********Desktoptest.docx"
     wordobj.ActiveDocument.SaveAs FileName:="********Desktoptest1", FileFormat:=12
     wordobj.Quit
     Set wordobj = Nothing
    

    But I’ve been facinf the situation when Excel automation hadn’t worked until setting the whole object «stairway».

    Suggestions:

    — Are you sure that exactly the last line causes an error?

    — Does FullDocName have an extension part?

    — Do you have more than one version of Office installed on this workstation?


    Andrey V Artemyev | Saint-Petersburg, Russia

    • Marked as answer by
      Bruce Song
      Friday, February 25, 2011 9:50 AM

Несмотря на интенсивный поиск в Google, я не могу понять, что в этом не так. Я все еще пропускаю ссылку или что-то в этом роде? Если вы видите, в чем ошибка, я буду вечно благодарен!

Рекомендации:

  • Visual Basic для приложений
  • Библиотека объектов Microsoft Excel 16.0
  • OLE автоматизация
  • Библиотека объектов Microsoft Office 16.0
  • RefEdit Control
  • Библиотека объектов Microsoft Word 16.0

Переменные:

Public appWord As Word.Application
Public sapmWord As Word.Document

Dim asNimi As String 'in this current sub

Код:

On Error Resume Next

Set appWord = GetObject(, "Word.Application")
If Err <> 0 Then
    Set appWord = CreateObject("Word.Application")
End If
On Error GoTo 0
appWord.Visible = True
Set sapmWord = appWord.documents.Open("C:ThisIsWorkingandDocOpens.docx")
'sapmWord.Activate 'doesn't make a difference

With sapmWord
    Selection.EndKey Unit = wdStory 'this line is first line to give an error. With or without a dot in the beginning of line.
    Selection.TypeText Text:=asNimi 'this line too, if previous is commented
'...and so on!
End With

sapmWord.Close savechanges:=True
Set appWord = Nothing
Set sapmWord = Nothing


Ответы
4

Чтобы использовать With, вы должны ссылаться на участников с .:

With sapmWord
    .Selection.EndKey Unit = wdStory
    .Selection.TypeText Text:=asNimi
End With

SapmWord — это текстовый документ. Текстовый документ не имеет метода selection. Он есть в объекте приложения Word, так что, вероятно, вы имеете в виду (и да, вам нужен ‘.’)

With appWord 
    .Selection.EndKey Unit:= wdStory 
    .Selection.TypeText Text:=asNimi 
    '...and so on!
End With

В конце концов, мне ничего не оставалось, как добавить закладки в документ Word и заполнить их VBA. Я до сих пор не понимаю, почему эти исходные коды не работали в моем коде, хотя они работают для других. Спасибо всем за помощь, может быть, кто-то еще получит здесь ответы.

Вам необходимо изменить sapmWord.Close savechanges: = True для appWord.quit savechanges: = True

Другие вопросы по теме

  1. 01-21-2005, 08:06 AM


    #1

    john.9.williams@bt.com


    Guest

    Dim Appword As word.application

    Hi

    I am using this daclaration in a program

    «Dim Appword As word.application»

    when i run my program i get this error assigned to this

    «Compile error userdefined type not defined»

    I know i have to do something but not sure what, any help greatly
    received

    Johny


  2. 01-21-2005, 08:06 AM


    #2

    RE: Dim Appword As word.application

    Use:

    Set AppWord=CreateObject(«Word.Application»)

    OR:

    Add the Word object library reference to your project

    «john.9.williams@bt.com» wrote:


    > Hi
    >
    > I am using this daclaration in a program
    >
    > «Dim Appword As word.application»
    >
    > when i run my program i get this error assigned to this
    >
    > «Compile error userdefined type not defined»
    >
    > I know i have to do something but not sure what, any help greatly
    > received
    >
    > Johny
    >
    >


  3. 01-21-2005, 09:06 AM


    #3

    john.9.williams@bt.com


    Guest

    Re: Dim Appword As word.application

    Where would i use the Set appWord = CreateObject(«Word.Application»)
    syntax

    AA2e72E wrote:


    > Use:
    >
    > Set AppWord=CreateObject(«Word.Application»)
    >
    > OR:
    >
    > Add the Word object library reference to your project
    >
    > «john.9.williams@bt.com» wrote:
    >
    > > Hi
    > >
    > > I am using this daclaration in a program
    > >
    > > «Dim Appword As word.application»
    > >
    > > when i run my program i get this error assigned to this
    > >
    > > «Compile error userdefined type not defined»
    > >
    > > I know i have to do something but not sure what, any help greatly
    > > received
    > >
    > > Johny
    > >
    > >


  4. 01-21-2005, 09:06 AM


    #4

    Re: Dim Appword As word.application

    Have you created a reference to the Word type library? Go to
    Tools>References, scroll down to Microsoft Word, and check it.


    HTH

    Bob Phillips

    <john.9.williams@bt.com> wrote in message
    news:1106306463.949876.325750@c13g2000cwb.googlegroups.com…


    > Hi
    >
    > I am using this daclaration in a program
    >
    > «Dim Appword As word.application»
    >
    > when i run my program i get this error assigned to this
    >
    > «Compile error userdefined type not defined»
    >
    > I know i have to do something but not sure what, any help greatly
    > received
    >
    > Johny
    >


  5. 01-21-2005, 09:06 AM


    #5

    Re: Dim Appword As word.application

    «AA2e72E» <AA2e72E@discussions.microsoft.com> wrote in message
    news:BA99EFE0-24A1-4168-82BF-364B1BDAA6BA@microsoft.com…
    > Use:
    >
    > Set AppWord=CreateObject(«Word.Application»)
    >

    You would also need

    Dim AppWord As Object


  6. 01-21-2005, 10:06 AM


    #6

    Re: Dim Appword As word.application

    See
    http://www.erlandsendata.no/english/…baoleolebasics
    http://www.erlandsendata.no/english/…olecontrolword

    HTH. Best wishes Harald

    <john.9.williams@bt.com> skrev i melding
    news:1106309477.009197.74890@z14g2000cwz.googlegroups.com…


    > Where would i use the Set appWord = CreateObject(«Word.Application»)
    > syntax


  7. 01-21-2005, 10:06 AM


    #7

    Re: Dim Appword As word.application

    You would do that instead of

    Set AppWord = New Word.Application

    but note my other post.

    HTH

    RP
    (remove nothere from the email address if mailing direct)

    <john.9.williams@bt.com> wrote in message
    news:1106309477.009197.74890@z14g2000cwz.googlegroups.com…


    > Where would i use the Set appWord = CreateObject(«Word.Application»)
    > syntax
    >
    >
    > AA2e72E wrote:
    > > Use:
    > >
    > > Set AppWord=CreateObject(«Word.Application»)
    > >
    > > OR:
    > >
    > > Add the Word object library reference to your project
    > >
    > > «john.9.williams@bt.com» wrote:
    > >
    > > > Hi
    > > >
    > > > I am using this daclaration in a program
    > > >
    > > > «Dim Appword As word.application»
    > > >
    > > > when i run my program i get this error assigned to this
    > > >
    > > > «Compile error userdefined type not defined»
    > > >
    > > > I know i have to do something but not sure what, any help greatly
    > > > received
    > > >
    > > > Johny
    > > >
    > > >

    >


  8. 01-21-2005, 11:06 AM


    #8

    Re: Dim Appword As word.application

    Why not spend a few minutes reading the «instructions» and save yourself
    time spent struggling later:

    As I previously posted:

    Microsoft Office 2000 Automation Help File Available (Q260410)
    http://support.microsoft.com/default…b;EN-US;260410

    Microsoft Office XP Automation Help File Available (Q302460)
    http://support.microsoft.com/default…b;EN-US;302460


    Regards,
    Tom Ogilvy

    <john.9.williams@bt.com> wrote in message
    news:1106309477.009197.74890@z14g2000cwz.googlegroups.com…


    > Where would i use the Set appWord = CreateObject(«Word.Application»)
    > syntax
    >
    >
    > AA2e72E wrote:
    > > Use:
    > >
    > > Set AppWord=CreateObject(«Word.Application»)
    > >
    > > OR:
    > >
    > > Add the Word object library reference to your project
    > >
    > > «john.9.williams@bt.com» wrote:
    > >
    > > > Hi
    > > >
    > > > I am using this daclaration in a program
    > > >
    > > > «Dim Appword As word.application»
    > > >
    > > > when i run my program i get this error assigned to this
    > > >
    > > > «Compile error userdefined type not defined»
    > > >
    > > > I know i have to do something but not sure what, any help greatly
    > > > received
    > > >
    > > > Johny
    > > >
    > > >

    >


  9. 01-21-2005, 11:06 AM


    #9

    Re: Dim Appword As word.application

    You need to set a reference to the Word object library. In VBA,
    go to the Tools menu, choose References, and scroll down to
    Microsoft Word. Check that box.


    Cordially,
    Chip Pearson
    Microsoft MVP — Excel
    Pearson Software Consulting, LLC
    www.cpearson.com

    <john.9.williams@bt.com> wrote in message
    news:1106306463.949876.325750@c13g2000cwb.googlegroups.com…


    > Hi
    >
    > I am using this daclaration in a program
    >
    > «Dim Appword As word.application»
    >
    > when i run my program i get this error assigned to this
    >
    > «Compile error userdefined type not defined»
    >
    > I know i have to do something but not sure what, any help
    > greatly
    > received
    >
    > Johny
    >


    Option Explicit

    Dim appWord As Word.Application

    Dim docWord As Word.Document

    Dim i As Integer

    Private Sub cmdStep1_Click()

    If appWord.Documents.Count = 0 Then

        Set docWord = appWord.Documents.Add

    End If

    Call InsertTable

    End Sub

    Private Sub cmdStep2_Click()

    If appWord.Documents.Count = 0 Then

        MsgBox «Run step 1, then step2.»

    Else

        Call InsertTable

    End If

    End Sub

    Private Sub cmdQuit_Click()

    Unload Me

    End Sub

    Private Sub Form_Load()

    Set appWord = New Word.Application

    appWord.Visible = False

    i = 1

    End Sub

    Sub InsertTable()

    Dim rngCurrent As Word.Range

    Dim objTable As Word.Table

    docWord.PageSetup.LeftMargin = 60

    Set rngCurrent = docWord.Range

    With rngCurrent

        .InsertParagraphAfter

        .Collapse Direction:=wdCollapseEnd

        .Text = «Table No. » & CStr(i) & «: TableName»

        i = i + 1

        .Font.Name = «Times New Roman»

        .Font.Size = 14

        .Font.Italic = True

        .ParagraphFormat.Alignment = wdAlignParagraphLeft

    End With

    Set rngCurrent = docWord.Range

    With rngCurrent

        .InsertParagraphAfter

        .Collapse Direction:=wdCollapseEnd

    End With

    Set objTable = docWord.Tables.Add(Range:=rngCurrent, NumRows:=4, NumColumns:=15)

    With objTable

        .Borders.Enable = True

        .Rows.Height = 10

        .Columns(1).Width = CentimetersToPoints(1.04)

        .Columns(2).Width = CentimetersToPoints(2.33)

        .Columns(3).Width = CentimetersToPoints(1.06)

        .Columns(4).Width = CentimetersToPoints(1.16)

        .Columns(5).Width = CentimetersToPoints(1.16)

        .Columns(6).Width = CentimetersToPoints(1.06)

        .Columns(7).Width = CentimetersToPoints(1.06)

        .Columns(8).Width = CentimetersToPoints(1.47)

        .Columns(9).Width = CentimetersToPoints(1.69)

        .Columns(10).Width = CentimetersToPoints(1.07)

        .Columns(11).Width = CentimetersToPoints(1.07)

        .Columns(12).Width = CentimetersToPoints(1.07)

        .Columns(13).Width = CentimetersToPoints(1.07)

        .Columns(14).Width = CentimetersToPoints(1.2)

        .Columns(15).Width = CentimetersToPoints(1.2)

    End With

    appWord.Visible = True

    End Sub

    Private Sub Form_Unload(Cancel As Integer)

    If docWord Is Nothing Then

        appWord.Quit wdDoNotSaveChanges

        Set appWord = Nothing

        Exit Sub

    End If

    If docWord.Saved Then

        docWord.Close wdDoNotSaveChanges

        Set docWord = Nothing

        appWord.Quit wdDoNotSaveChanges

        Set appWord = Nothing

    Else

        MsgBox «Save changes before quit.»

        Cancel = True

    End If

    End Sub

Здравствуйте, друзья! Столкнулся с такой проблемой — сделал простенькую базу в Access 2007 (mdb) в которой хранится список литературы. В базе форма с парой окон для отображения содержимого записи и кнопка «Вставить» при нажатии которой, название выбранной книги вставляется в открытый (активный) документ Word. Реализовал я сию процедуру таким образом:

Visual Basic
1
2
3
4
5
6
7
8
Private Sub InsertToWord_Click()
Dim AppWord As Word.Application
 
Set AppWord = Word.Application
 
AppWord.ActiveWindow.Selection.TypeText Text:=[Название]
 
Exit Sub

Ну соответственно подключил библиотеку Вордовскую.
И все вроде работает, да нет-нет, при попытке экспортировать текст в только что открытый документ выдает такую ошибку:
Run-time error ‘462’
The remote server machine does not exist or unavailable

И исчезает она либо после двух-трех нажатий сама, либо после перезапуска базы данных.
Пробовал без создания объекта Word.Application — та же история. Пробовал создавать объект при помощи CreateObject — пишет человечьм (русским) языком, мол ни один документ не открыт, при этом в действительности открытый документ я лицезрею своими глазами…
Причем, абсолютно та же картина при попытке повторить трюк из Excel.
Как с этим бороться ума не приложу! Может кто подскажет?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Old

11-25-2011, 08:29 AM

tinfanide
tinfanide is offline

Why it works but the macro is error in VB? Windows 7 64bit Why it works but the macro is error in VB? Office 2010 32bit

Expert

Why it works but the macro is error in VB?

 

Join Date: Aug 2011

Posts: 312

tinfanide is on a distinguished road

Default

Why it works but the macro is error in VB?


The macro runs well but when I press F5 in VB, it always returns «runtime error: 462» when it comes to the saveAs method.

Code:

Private Sub copytoWord_Click()
     
    Dim AppWord         As Word.Application
     
    Set AppWord = CreateObject("Word.Application")
    AppWord.Visible = True
    
    Sheets("Sheet1").Range("A1:B4").Copy
    AppWord.Documents.Add
  
    AppWord.Selection.Paste
     
    Application.CutCopyMode = False
     
     
   With ActiveDocument
   .SaveAs2 "C:UsersTinDesktop" & "Book1", wdFormatDocumentDefault
   End With
    
    Set AppWord = Nothing
    
     
End Sub

Reply With Quote

Old

11-30-2011, 04:28 AM

Default


Hi Tinfanide,

The error is probably because you’re not telling the calling App that it’s AppWord’s ActiveDocument you want to save. Try something along the lines of:

Code:

Private Sub copytoWord_Click()
Sheets("Sheet1").Range("A1:B4").Copy
Dim AppWord As Word.Application
Set AppWord = CreateObject("Word.Application")
With AppWord
  .Visible = True
  .Documents.Add
  .Selection.Paste
  .CutCopyMode = False
  .ActiveDocument.SaveAs2 "C:UsersTinDesktop" & "Book1", wdFormatDocumentDefault
  .Quit
End With
Set AppWord = Nothing
End Sub

__________________
Cheers,
Paul Edstein
[Fmr MS MVP — Word]

Reply With Quote

Old

12-02-2011, 05:16 AM

tinfanide
tinfanide is offline

Why it works but the macro is error in VB? Windows 7 64bit Why it works but the macro is error in VB? Office 2010 32bit

Expert

Why it works but the macro is error in VB?

 

Join Date: Aug 2011

Posts: 312

tinfanide is on a distinguished road

Default


Quote:

Originally Posted by macropod
View Post

Hi Tinfanide,

Code:

Dim AppWord As Word.Application

Excel reports:
User-defined type not defined

Reply With Quote

Old

12-02-2011, 07:39 PM

tinfanide
tinfanide is offline

Why it works but the macro is error in VB? Windows 7 64bit Why it works but the macro is error in VB? Office 2010 32bit

Expert

Why it works but the macro is error in VB?

 

Join Date: Aug 2011

Posts: 312

tinfanide is on a distinguished road

Default


Quote:

Originally Posted by tinfanide
View Post

Excel reports:
User-defined type not defined

I forgot to add MS Word Object Library.

Reply With Quote

Old

12-02-2011, 08:00 PM

tinfanide
tinfanide is offline

Why it works but the macro is error in VB? Windows 7 64bit Why it works but the macro is error in VB? Office 2010 32bit

Expert

Why it works but the macro is error in VB?

 

Join Date: Aug 2011

Posts: 312

tinfanide is on a distinguished road

Default


Code:

Private Sub CopyToWord()

Dim arr As Variant
arr = Array("A", "B", "C")

With ActiveSheet
.Cells.Clear

For x = 1 To 3
.Range(arr(x - 1) & "1").Value = x
Next x

.Range("A1:C1").Copy

End With

Dim AppWord As Word.Application
Set AppWord = CreateObject("Word.Application")

With AppWord

.Visible = True
.Documents.Add
.Selection.Paste

End With

'''''''''''''''''''''''''''
With AppWord.ActiveDocument.Tables(0)
.Delete
End With
'''''''''''''''''''''''''''

Set AppWord = Nothing

End Sub

Same problem with the highlighted bit
Reported «Application defined or object defined error»

I remember I’ve learnt to set variable for the table
But here I don’t know how to select the table in Word from Excel VBA

And
I want to select the table
as the .Paste command auto copy the Excel data to Word in a table format
I want to do something to the table
like deleting it, adding borders or some styles to it

So
I want to ask how I can control the word table from Excel VBA

Many thanks.

Reply With Quote

Old

12-03-2011, 12:53 AM

Default


Hi Tinfanide,

The line:
Dim AppWord As Word.Application
is only relevant if you’ve already set a reference to Word.

Try:

Code:

Private Sub CopyToWord()
Dim arr As Variant, x As Long, AppWord As Object
Set AppWord = CreateObject("Word.Application")
arr = Array("A", "B", "C")
With ActiveSheet
  .Cells.Clear
  For x = 1 To 3
    .Range(arr(x - 1) & "1").Value = x
  Next x
  .Range("A1:C1").Copy
End With
With AppWord
  .Visible = True
  .Documents.Add
  With .ActiveDocument
    .Range.Paste
    .Tables(1).Delete
    '.Close SaveChanges:=False
  End With
  '.Quit
End With
Set AppWord = Nothing
End Sub

The two commented-out lines show how to correctly shut down Word without saving. Simply setting AppWord = Nothing doesn’t do that — it leaves Word running and, if you re-run the code, another Word instance will be created.

__________________
Cheers,
Paul Edstein
[Fmr MS MVP — Word]

Reply With Quote

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Appvlp exe ошибка при запуске приложения
  • Appstore ошибка при загрузке