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
|
Несмотря на интенсивный поиск в 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
Другие вопросы по теме
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 | ||
|
Ну соответственно подключил библиотеку Вордовскую.
И все вроде работает, да нет-нет, при попытке экспортировать текст в только что открытый документ выдает такую ошибку:
Run-time error ‘462’
The remote server machine does not exist or unavailable
И исчезает она либо после двух-трех нажатий сама, либо после перезапуска базы данных.
Пробовал без создания объекта Word.Application — та же история. Пробовал создавать объект при помощи CreateObject — пишет человечьм (русским) языком, мол ни один документ не открыт, при этом в действительности открытый документ я лицезрею своими глазами…
Причем, абсолютно та же картина при попытке повторить трюк из Excel.
Как с этим бороться ума не приложу! Может кто подскажет?
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
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
![]()
asked Jun 26, 2018 at 7:54
![]()
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
![]()
FunThomasFunThomas
21.8k3 gold badges18 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
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_ᴅᴇᴠLS_ᴅᴇᴠ
10.8k1 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
![]()
- Remove From My Forums
-
Question
-
Hi,
I have a problem with the Microsoft.Office.Interop.Word library (version:11.0.0.0). I add the library as reference to my project in VS2008 Framework 3.5 SP1 to open a Word 2003 file.
This is a sample code that i’m using:
//some code before..... ApplicationClass wordapp = new ApplicationClass(); //docName is the file path Document worddoc = wordapp.Documents.Open(ref docName, ref missingValue, ref missingValue, ref missingValue, ref missingValue,ref missingValue,ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue,ref missingValue, ref missingValue, ref missingValue, ref missingValue); //some code after ...
When i try to use the «Open» method it raise an exception which is
Unable to cast COM object of type ‘Microsoft.Office.Interop.Word.ApplicationClass’ to interface type ‘Microsoft.Office.Interop.Word._Application’. This operation failed because the QueryInterface call on the COM component for the interface with IID ‘{00020970-0000-0000-C000-000000000046}’ failed due to the following error: Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED)).
I tried to solve it in so many ways but i can’t find the solution.
Please,i need your help!
Thank you so much.
P.S. If you need more informations (settings and so on)…tell me!
Answers
-
I’ve just re-installed VS 2008 and Office 2003.
I don’t know why but now it works,maybe there was something wrong in one of those.
Thanks for the support.bye
-
Marked as answer by
Monday, April 12, 2010 4:17 PM
-
Marked as answer by
-
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
receivedJohny
-
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
>
>
-
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»)
syntaxAA2e72E 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
> >
> >
-
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.—
HTHBob 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
>
-
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
-
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/…olecontrolwordHTH. 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
-
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
> > >
> > >
>
-
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;260410Microsoft 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
> > >
> > >
>
-
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
>
