Vba word печать документа

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Application.PrintOut method (Word)

vbawd10.chm158335424

vbawd10.chm158335424

word

Word.Application.PrintOut

f795218e-cd49-f3ac-c03d-9a9424361392

06/08/2017

medium

Application.PrintOut method (Word)

Prints all or part of the specified document.

Syntax

expression.PrintOut (Background, Append, Range, OutputFileName, From, To, Item, Copies, Pages, PageType, PrintToFile, Collate, FileName, ActivePrinterMacGX, ManualDuplexPrint, PrintZoomColumn, PrintZoomRow, PrintZoomPaperWidth, PrintZoomPaperHeight)

expression Required. A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
Background Optional Variant Set to True to have the macro continue while Microsoft Word prints the document.
Append Optional Variant Set to True to append the specified document to the file name specified by the OutputFileName argument. False to overwrite the contents of OutputFileName.
Range Optional Variant The page range. Can be any WdPrintOutRange constant.
OutputFileName Optional Variant If PrintToFile is True, this argument specifies the path and file name of the output file.
From Optional Variant The starting page number when Range is set to wdPrintFromTo.
To Optional Variant The ending page number when Range is set to wdPrintFromTo.
Item Optional Variant The item to be printed. Can be any WdPrintOutItem constant.
Copies Optional Variant The number of copies to be printed.
Pages Optional Variant The page numbers and page ranges to be printed, separated by commas. For example, «2, 6-10» prints page 2 and pages 6 through 10.
PageType Optional Variant The type of pages to be printed. Can be any WdPrintOutPages constant.
PrintToFile Optional Variant True to send printer instructions to a file. Make sure to specify a file name with OutputFileName.
Collate Optional Variant When printing multiple copies of a document, True to print all pages of the document before printing the next copy.
FileName Optional Variant The path and file name of the document to be printed. If this argument is omitted, Word prints the active document. (Available only with the Application object.)
ActivePrinterMacGX Optional Variant This argument is available only in Microsoft Office Macintosh Edition. For additional information about this argument, consult the language reference Help included with Microsoft Office Macintosh Edition.
ManualDuplexPrint Optional Variant True to print a two-sided document on a printer without a duplex printing kit. If this argument is True, the PrintBackground and PrintReverse properties are ignored. Use the PrintOddPagesInAscendingOrder and PrintEvenPagesInAscendingOrder properties to control the output during manual duplex printing. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
PrintZoomColumn Optional Variant The number of pages you want Word to fit horizontally on one page. Can be 1, 2, 3, or 4. Use with the PrintZoomRow argument to print multiple pages on a single sheet.
PrintZoomRow Optional Variant The number of pages you want Word to fit vertically on one page. Can be 1, 2, or 4. Use with the PrintZoomColumn argument to print multiple pages on a single sheet.
PrintZoomPaperWidth Optional Variant The width to which you want Word to scale printed pages, in twips (20 twips = 1 point; 72 points = 1 inch).
PrintZoomPaperHeight Optional Variant The height to which you want Word to scale printed pages, in twips (20 twips = 1 point; 72 points = 1 inch).

Example

This example prints the current page of the active document.

ActiveDocument.PrintOut Range:=wdPrintCurrentPage

This example prints all the documents in the current folder. The Dir function is used to return all file names that have the file name extension «.doc».

adoc = Dir("*.DOC") 
Do While adoc <> "" 
 Application.PrintOut FileName:=adoc 
 adoc = Dir() 
Loop

This example prints the first three pages of the document in the active window.

ActiveDocument.ActiveWindow.PrintOut _ 
 Range:=wdPrintFromTo, From:="1", To:="3"

This example prints the comments in the active document.

If ActiveDocument.Comments.Count >= 1 Then 
 ActiveDocument.PrintOut Item:=wdPrintComments 
End If

This example prints the active document, fitting six pages on each sheet.

ActiveDocument.PrintOut PrintZoomColumn:=3, _ 
 PrintZoomRow:=2

This example prints the active document at 75% of actual size.

ActiveDocument.PrintOut _ 
 PrintZoomPaperWidth:=0.75 * (8.5 * 1440), _ 
 PrintZoomPaperHeight:=0.75 * (11 * 1440)

See also

Application Object

[!includeSupport and feedback]

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Window.PrintOut method (Word)

vbawd10.chm157417917

vbawd10.chm157417917

word

Word.Window.PrintOut

63ea2dd2-5b3c-1239-16ce-1b4980cde3d3

06/08/2017

medium

Window.PrintOut method (Word)

Prints all or part of the document displayed in the specified window.

Syntax

expression.PrintOut (Background, Append, Range, OutputFileName, From, To, Item, Copies, Pages, PageType, PrintToFile, Collate, FileName, ActivePrinterMacGX, ManualDuplexPrint, PrintZoomColumn, PrintZoomRow, PrintZoomPaperWidth, PrintZoomPaperHeight)

expression Required. A variable that represents a Window object.

Parameters

Name Required/Optional Data type Description
Background Optional Variant Set to True to have the macro continue while Microsoft Word prints the document.
Append Optional Variant Set to True to append the specified document to the file name specified by the OutputFileName argument. False to overwrite the contents of OutputFileName.
Range Optional Variant The page range. Can be any WdPrintOutRange constant.
OutputFileName Optional Variant If PrintToFile is True, this argument specifies the path and file name of the output file.
From Optional Variant The starting page number when Range is set to wdPrintFromTo.
To Optional Variant The ending page number when Range is set to wdPrintFromTo.
Item Optional Variant The item to be printed. Can be any WdPrintOutItem constant.
Copies Optional Variant The number of copies to be printed.
Pages Optional Variant The page numbers and page ranges to be printed, separated by commas. For example, «2, 6-10» prints page 2 and pages 6 through 10.
PageType Optional Variant The type of pages to be printed. Can be any WdPrintOutPages constant.
PrintToFile Optional Variant True to send printer instructions to a file. Make sure to specify a file name with OutputFileName.
Collate Optional Variant When printing multiple copies of a document, True to print all pages of the document before printing the next copy.
FileName Optional Variant The path and file name of the document to be printed. If this argument is omitted, Word prints the active document. (Available only with the Application object.)
ActivePrinterMacGX Optional Variant This argument is available only in Microsoft Office Macintosh Edition. For additional information about this argument, consult the language reference Help included with Microsoft Office Macintosh Edition.
ManualDuplexPrint Optional Variant True to print a two-sided document on a printer without a duplex printing kit. If this argument is True, the PrintBackground and PrintReverse properties are ignored. Use the PrintOddPagesInAscendingOrder and PrintEvenPagesInAscendingOrder properties to control the output during manual duplex printing. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
PrintZoomColumn Optional Variant The number of pages you want Word to fit horizontally on one page. Can be 1, 2, 3, or 4. Use with the PrintZoomRow argument to print multiple pages on a single sheet.
PrintZoomRow Optional Variant The number of pages you want Word to fit vertically on one page. Can be 1, 2, or 4. Use with the PrintZoomColumn argument to print multiple pages on a single sheet.
PrintZoomPaperWidth Optional Variant The width to which you want Word to scale printed pages, in twips (20 twips = 1 point; 72 points = 1 inch).
PrintZoomPaperHeight Optional Variant The height to which you want Word to scale printed pages, in twips (20 twips = 1 point; 72 points = 1 inch).

Example

This example prints the current page of the active document.

ActiveDocument.PrintOut Range:=wdPrintCurrentPage

This example prints all the documents in the current folder. The Dir function is used to return all file names that have the file name extension «.doc».

adoc = Dir("*.DOC") 
Do While adoc <> "" 
 Application.PrintOut FileName:=adoc 
 adoc = Dir() 
Loop

This example prints the first three pages of the document in the active window.

ActiveDocument.ActiveWindow.PrintOut _ 
 Range:=wdPrintFromTo, From:="1", To:="3"

This example prints the comments in the active document.

If ActiveDocument.Comments.Count >= 1 Then 
 ActiveDocument.PrintOut Item:=wdPrintComments 
End If

This example prints the active document, fitting six pages on each sheet.

ActiveDocument.PrintOut PrintZoomColumn:=3, _ 
 PrintZoomRow:=2

This example prints the active document at 75% of actual size.

ActiveDocument.PrintOut _ 
 PrintZoomPaperWidth:=0.75 * (8.5 * 1440), _ 
 PrintZoomPaperHeight:=0.75 * (11 * 1440)

See also

Window Object

[!includeSupport and feedback]

I want to print a Word document, mydocument.docx, from a button in an Excel sheet. Both are in the same folder.

I don’t want users to see the Word document. They just click the button in Excel.

I can create a button in Excel and make it open an empty vb. This is as much as I know. If you can explain this in steps that would be so awesome.

Community's user avatar

asked Sep 14, 2009 at 5:34

nickjohn's user avatar

You can use the Word automation object model to gain programmatic access to Word.

In almost all cases, you’d be following these steps:

  1. Create the Word application object.
  2. Open a document.
  3. Do something with the document.
  4. Close the document.
  5. Quit the Word application.

Here is what the basic VBA code looks like:

' Step 1
Dim objWord
Set objWord = CreateObject("Word.Application")
' Hidden window!
objWord.Visible = False
' Save the original printer, otherwise you will reset the system default!
Dim previousPrinter
Set previousPrinter = objWord.ActivePrinter
objWord.ActivePrinter = "My Printer Name"

' Step 2
Dim objDoc
Set objDoc = objWord.Documents.Open("C:TestSomeDocument.docx")

' Step 3 -- in this case, print out the document without any prompts
objDoc.PrintOut
' Restore the original printer
objWord.ActivePrinter = previousPrinter

' Step 4
objDoc.Close

' Step 5
objWord.Quit

answered Sep 14, 2009 at 6:24

bobbymcr's user avatar

bobbymcrbobbymcr

23.6k3 gold badges55 silver badges66 bronze badges

4

The following code will print out a word document.

'---------------------------------------------------------------------------------------
' Procedure : PrintDoc
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Print a Word Document
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and 
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' strDoc - The path and filename of the document to be printed
' intCopies - The number of copies to be printed
'
' Usage:
' ~~~~~~~~~~~~~~~~
' PrintDoc("c:managementevaluation.doc",1)
'---------------------------------------------------------------------------------------
Function PrintDoc(strDoc As String, intCopies As Integer)
   Dim WordObj As Object

   Set WordObj = CreateObject("Word.Application")

   WordObj.Documents.Open strDoc
   WordObj.PrintOut Background:=False, Copies:=intCopies
   WordObj.Documents.Close SaveChanges:=wdDoNotSaveChanges
   WordObj.Quit

   Set WordObj = Nothing
 End Function

9.4.8. PrintOut — распечатка документов

PrintOut предназначен для вывода документов на печать. Например, следующий код (листинг 9.14.) выводит на печать все документы Microsoft Word 2007 (то есть — с расширениями docx и docm ), расположенные в корневом каталоге диска C.

var_Doc = Dir("C:*.doc?")
Do While var_Doc <> ""
    Application.PrintOut FileName:=var_Doc
    var_Doc = Dir()
Loop


Листинг
9.14.
Печать всех документов из корневого каталога диска C

Метод PrintOut существует для различных объектов и может принимать множество параметров, управляющих всеми тонкостями печати. Например, с помощью такого кода (листинг 9.15.) мы можем распечатать первые пять страниц текущего документа:

ActiveDocument.ActiveWindow.PrintOut _
Range:=wdPrintFromTo, From:="1", To:="5"


Листинг
9.15.
Вывод на печать первых 5 страниц текущего документа

9.4.9. Quit — выход из приложения

Quit используется для выхода из приложения (листинг 9.16.):

Application.Quit


Листинг
9.16.
Выход из приложения

9.4.10. Run — запуск макросов

Run позволяет запускать макросы и, при необходимости, передавать им параметры (до 30). При вызове методу Run передается имя, состоящее из имени проекта, имени модуля, и, собственно, имени макроса. Например, запуск макроса MyMacros, расположенного в модуле NewModule проекта Project1 выглядит так (листинг 9.17.):

Application.Run ("Project1.NewModule.MyMacros")


Листинг
9.17.
Запуск макроса с помощью метода Run

Параметры, передаваемые макросу, перечисляются после его имени через запятую.

9.4.11. ScreenRefresh — принудительное обновление экрана

ScreenRefresh позволяет принудительно обновить экран. Используется обычно в комбинации с запретом автоматического обновления экрана (свойство Application.ScreenUpdating, его мы рассмотрим ниже). Как правило, обновление экрана делают через некоторые промежутки времени — тогда у пользователя не возникает ощущения, что программа зависла.

Теперь рассмотрим наиболее полезные свойства объекта Application.

9.5. Свойства объекта Application

9.5.1. ActiveDocument и другие — активный документ

ActiveDocument возвращает объект активного документа — того, который открыт в данный момент в Microsoft Word для редактирования. У объекта ActiveDocument есть множество полезных свойств и методов. Мы обсудим их при разговоре об объекте Document.

Например, в листинге 9.18 мы выводим в окне сообщения имя активного документа.

MsgBox Application.ActiveDocument.Name


Листинг
9.18.
Вывод имени активного документа

Надо отметить, что нельзя модифицировать свойство ActiveDocument — то есть не можем с его помощью сделать неактивный документ активным. Чтобы сделать документ активным, используют специальный метод объекта Document.

Существует немало других свойств Application, имена которых начинаются с Active.

ActivePrinter возвращает объект активного принтера — устройства, используемого для печати документов по умолчанию.

ActiveWindow возвращает активное окно — объект типа Window.

9.5.2. CapsLock — текущее состояние Caps Lock

CapsLock показывает текущее состояние режима Caps Lock. Если этот режим активен, по умолчанию при вводе с клавиатуры вводятся прописные буквы. Если режим Caps Lock включен — свойство возвращает True, если выключен — False.

9.5.3. Caption — заголовок окна MS Word

Caption позволяет узнать, и, при желании, изменить заголовок окна Microsoft Word.

Например код в листинге 9.19. меняет словосочетание Microsoft Word в заголовке окна на слова «Моя программа».

Application.Caption = "Моя программа"


Листинг
9.19.
Изменение заголовка окна MS Word

9.5.4. CustomizationContext — область сохранения настроек

CustomizationContext позволяет узнавать и задавать документ и шаблон, в котором сохраняются такие настройки, как изменения в настройке меню, панелей инструментов, горячих клавиш. Чтобы узнать текущую область настройки, достаточно выполнить код из листинга 9.20.

MsgBox Application.CustomizationContext


Листинг
9.20.
Узнаем область сохранения настроек

Чтобы установить в качестве области настройки шаблон Normal.dotm (то есть — сделать настройки доступными для всех документов), достаточно воспользоваться кодом листинга 9.21.:

CustomizationContext = NormalTemplate


Листинг
9.21.
Будем сохранять изменения настроек в Normal.dotm

Обратите внимание на то, что в предыдущих версиях MS Word этот шаблон назывался Normal.dot.

Для сохранения изменений в шаблоне, присоединенном к активному документу, можно воспользоваться командой из листинга 9.22.:

CustomizationContext = ActiveDocument.AttachedTemplate


Листинг
9.22.
Сохраняем изменения в присоединенном шаблоне

Для сохранения изменений лишь в текущем документе, можно использовать команду из листинга 9.23.

CustomizationContext = ThisDocument


Листинг
9.23.
Сохраняем изменения в присоединенном шаблоне

9.5.5. Dialogs — диалоговые окна MS Word

09-04-Dialogs.docm — пример к п. 9.5.5.

Dialogs возвращает коллекцию Dialogs (Диалоговые окна), которая дает доступ ко всем диалоговым окнам Microsoft Word. Если выполнить код листинга 9.24., можно узнать количество объектов в коллекции Dialogs.

MsgBox ("Количество окон в коллекции Dialogs:" + _
    Str(Application.Dialogs.Count))


Листинг
9.24.
Количество диалоговых окон в коллекции Dialogs

Чтобы отобразить диалоговое окно поиска строк в документе, можно использовать код, представленный в листинге 9.25.

Dim obj_FindS As Dialog
    Set obj_FindS = Dialogs(wdDialogEditFind)
    With obj_FindS
        .Find = "Строка"
        .Show
    End With


Листинг
9.25.
Запуск диалогового окна поиска строк в документе

Здесь мы объявляем объектную переменную типа Dialog, создаем ссылку на окно поиска строк в документе — это окно представлено константой wdDialogEditFind, после чего присваиваем свойству Find окна поиска значение «Строка» — именно это значение будет отображаться в строке поиска, и показываем окно поиска, используя метод Show. Похожим образом работают и с другими диалоговыми окнами. Их имена (около 230) можно найти в перечислении WdWordDialog.

9.5.6. DisplayAlerts — управление выводом сообщений

DisplayAlerts — позволяет управлять выводом диалоговых окон, сообщений об ошибках и т.д. при работе в Microsoft Word. Чтобы запретить вывод всех сообщений, используйте код, приведенный в листинге 9.26.

Application.DisplayAlerts = wdAlertsNone


Листинг
9.26.
Запрет вывода всех сообщений

Константа wdAlertsNone запрещает вывод сообщений. Аналогично, константа wdAlertsAll разрешает вывод всех сообщений, а wdAlertsMessageBox разрешает лишь вывод окон сообщений, сообщения об ошибках не выводятся.

9.5.7. EnableCancelKey — запрещаем остановку программы

09-05-Cancel.docm — пример к п. 9.5.7

EnableCancelKey — позволяет разрешать и запрещать пользователю остановку программы по нажатию сочетания клавиш Ctrl + Break. Это может быть полезно при выполнении участков кода, которые нельзя прерывать.

Для того чтобы запретить прерывание работы программы нужно присвоить этому свойству значение wdCancelDisabled, для разрешения — wdCancelInterrupt.

Пример использования этого оператора вы можете найти в листинге 9.27.

Dim num_b As Double
    MsgBox ("Вы не сможете прервать выполнение " + _
        "следующего кода")
    Application.EnableCancelKey = wdCancelDisabled
    For i = 1 To 1000000
        For j = 100 To 1 Step -1
            num_b = num_b * i / j
        Next j
    Next i
    Application.EnableCancelKey = wdCancelInterrupt
    MsgBox ("А теперь Ctrl + Pause Break " + _
        "снова работает")


Листинг
9.27.
Запрет прерывания выполнения программы

9.5.8. IsObjectValid — проверка объектных переменных

IsObjectValid — позволяет проверить объектную переменную. Если объект, на которую она ссылается, существует — проверка возвратит True, если нет — False. Это свойство полезно использовать для проверки объектов, которые могут быть удалены пользователем. Если объект существует, можно произвести с ним какие-либо действия. Если нет — сообщить причину, по которой действия невозможны.

9.5.9. KeyBindings — назначаем клавиатурные сокращения

KeyBindings — возвращает коллекцию KeyBindings, которая содержит информацию о клавиатурных привязках. Это очень полезная коллекция — с ее помощью можно, например, назначить клавиатурную комбинацию для запуска какого-нибудь макроса. листинг 9.28. позволяет назначить комбинацию клавиш Alt + Shift + T макросу TextEdit, хранящемуся в модуле MyMacros шаблона Normal.Dotm

Application.CustomizationContext = NormalTemplate
Application.KeyBindings.Add _
wdKeyCategoryMacro, _
"Normal.MyMacros.TextEdit", _
BuildKeyCode(wdKeyAlt, wdKeyShift, wdKeyT)


Листинг
9.28.
Программное назначение комбинации клавиш макросу

Сначала с помощью свойства CustomizationContext мы устанавливаем место, где будет сохранена привязка. Это — шаблон Normal.Dotm. Далее мы используем метод Add коллекции KeyBindings. Мы передаем этому методу три параметра. Первый ( wdKeyCategoryMacro ) указывает методу на то, что мы назначаем клавиатурную комбинацию макросу. Второй -» Normal.MyMacros.TextEdit » — указывает путь к макросу, запуск которого мы назначаем клавиатурному сокращению. Третий параметр содержит вызов метода BuildKeyCode — напомню, что он генерирует код сочетания клавиш на основе переданных ему параметров. В нашем случае он сгенерирует код для сочетания клавиш Alt + Shift + T — мы передали методу параметры wdKeyAlt, wdKeyShift и wdKeyT.

Если все сделано верно — в частности, макрос, запуск которого мы автоматизируем, существует — после выполнения такого кода нажатие выбранного сочетания клавиш в любом активном документе приведет к запуску этого макроса.

9.5.10. NumLock — состояние цифровой клавиатуры

NumLock возвращает состояние клавиши NumLock — True если цифровая клавиатура находится в режиме ввода цифр, иначе — False.

9.5.11. RecentFiles — недавно открытые файлы

RecentFiles — позволяет работать с файлами, которые вы недавно открывали. Список этих файлов можно увидеть в диалоговом окне открытия файлов. Последний файл, с которым вы работали, хранится в списке первым. Чтобы открыть его, можно воспользоваться кодом из листинга 9.29.

RecentFiles(1).Open


Листинг
9.29.
Открываем последний из недавно открытых файлов

9.5.12. ScreenUpdating — запрет обновления экрана

09-06-ScreenUpdating.docm — пример к п. 9.5.12.

Свойство ScreenUpdating используют для отключения обновления экрана во время вывода в документ большого количества информации или других действий с документом. Это позволяет ускорить работу, так как системные ресурсы не тратятся на постоянное обновление экрана. В листинге 9.30. мы запрещаем обновление экрана, выводим в документ 10000 строк, принудительно обновляя экран после каждой 1000 строк, после чего разрешаем автоматическое обновление.

Application.ScreenUpdating = False
    For i = 1 To 10
        For j = 1 To 1000
            Selection.TypeText ("Строка №" + Str(i * j))
            Selection.TypeParagraph
        Next j
        Application.ScreenRefresh
    Next i
    Application.ScreenUpdating = True


Листинг
9.30.
Запрет и разрешение обновления экрана

Очевидно, что присвоив False свойству ScreenUpdating мы запрещаем обновление экрана, а присвоив True — разрешаем.

Понравилась статья? Поделить с друзьями:
  • Vba word переход на новую строку
  • Vba word перенос таблиц в word
  • Vba word переместить курсор
  • Vba word перейти в начало документа
  • Vba word номер абзаца