Как запустить word в командной строке

Как и большинство приложений, вы можете запустить Word из командной строки. Word также поддерживает несколько дополнительных параметров для управления процессом запуска.

Независимо от того, вводите ли вы команду в командной строке, используете ее для создания ярлыка, вставляете ее как часть пакетного сценария, запуск Word с дополнительными параметрами позволяет выполнять такие действия:

  • запуск Word в безопасном режиме для устранения неполадок;
  • запуск с помощью определенного шаблона.

Чтобы открыть Word с помощью командной строки, нам нужно выяснить, в каком каталоге находится исполняемый файл winword.exe. Вы можете сделать это вручную или использовать командную строку. Для этого нажмите значок «Лупа» рядом с кнопкой «Пуск» и в поиске наберите  «cmd “ и откройте командную строку, выбрав приложение ”Командная строка».

вызов командной строки виндовс 10

Когда вы откроете командную строку, вы окажетесь в каталоге верхнего уровня—папке учетной записи пользователя. Нам нужно переместиться глубже, в каталог Program Files. Для этого введите следующую команду и нажмите клавишу Enter:

cd”program files (x86)”

смена каталога в командной строке

Теперь вы будете находиться в каталоге Program Files. Следующий шаг — найти каталог, в котором находится файл winword.exe. Для этого введите следующую команду и нажмите “Enter.”

dir winword.exe /s

После ввода этой команды вы увидите расположение искомого файла. На скриншоте выделено желтой рамкой.

поиск файла в командной строке

Теперь, когда вы знаете, где находится winword.exe-файл,  используйте команду cd, чтобы открыть путь к файлу. Введите следующую команду:

cd Microsoft OfficeOffice16

Теперь вы переместитесь в каталог, где расположен исполняемый файл winword. Чтобы открыть Microsoft Word так же, как если бы вы открывали его через значок, все, что вам нужно сделать, это ввести winword, а затем нажмите “Enter”. Word откроется обычным способом.

запуск ворда из командной строки

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

Запуск Word из командной строки с различными ключами и параметрами

Позаимствовано с официального сайта поддержки Microsoft Office, вот список некоторых возможных способов открыть Word, вместе с соответствующей командой.

Ключ и параметр Описание
/safe Запускает Word в безопасном режиме без каких-либо дополнительных надстроек, шаблонов и других настроек. Это полезно при устранении неполадок в Word.
Вы также можете запустить Word в безопасном режиме, удерживая клавишу Ctrl при запуске Word из меню Пуск
/q Запускает Word без отображения заставки Word.
/ttemplatename Запускает Word с новым документом на основе шаблона, отличного от обычного шаблона.
Пример: Предположим, мы хотели открыть документ, хранящийся на диске C под названием example.docx, тогда указываем следующую команду:/tc:example.docx  Примечание: не ставьте пробел между ключом и именем файла.
/t filename Запускает Word и открывает существующий файл.
Пример: чтобы запустить Word и открыть существующий файл пример.docx, хранящийся на диске C, введите следующее:/t c:пример.docx Чтобы открыть сразу несколько файлов, расположенные на диске C, введите следующее:/t c:пример.docx c:пример2.docx
/f filename Запускает Word с новым документом на основе существующего файла.
Пример: чтобы запустить Word и создать новый документ на основе файла пример.docx, хранящегося на рабочем столе, введите следующее:/f “C:UserspcuserDesktopпример.docx
/a Запускает Word и предотвращает автоматическую загрузку надстроек и глобальных шаблонов (включая обычный шаблон). Кроме того, он блокирует файлы настроек.
/m Запускает Word без запуска макросов AutoExec.
/n Запускает новый экземпляр Word без открытого документа. Документы, открытые в каждом экземпляре Word, не будут отображаться в списке переключателей Windows других экземпляров.
/r Перерегистрация Word в реестре Windows. Этот параметр запускает Word, запускает программу установки Office, обновляет реестр Windows и закрывает программу

Дорогой читатель! Вы посмотрели статью до конца.
Получили вы ответ на свой вопрос? Напишите в комментариях пару слов. Если ответа не нашли, укажите что искали или откройте содержание блога.

ОЧЕНЬ ВАЖНО! Оцени лайком или дизлайком статью!
Блог твой компьютер лайк   Блог твой компьютер дизлайк

Excel for Microsoft 365 Word for Microsoft 365 Outlook for Microsoft 365 PowerPoint for Microsoft 365 Access for Microsoft 365 Excel 2021 Word 2021 Outlook 2021 PowerPoint 2021 Access 2021 Excel 2019 Word 2019 Outlook 2019 PowerPoint 2019 Access 2019 Excel 2016 Word 2016 Outlook 2016 PowerPoint 2016 Access 2016 Excel 2013 Word 2013 Outlook 2013 PowerPoint 2013 Access 2013 Excel 2010 Word 2010 Outlook 2010 PowerPoint 2010 Access 2010 Excel 2007 Word 2007 Outlook 2007 PowerPoint 2007 Access 2007 More…Less

When you launch a Microsoft Office product, the startup process runs in a standard way. Microsoft Word, for example, displays the Word splash screen and loads the Normal template. But suppose you want Word to start without its splash screen and then load a template other than the Normal template. Or, you want to customize the process even more by loading an add-in or running a macro upon startup. You can add options like this by using subcommands called command-line switches to an Office app’s startup command.

If you want to use the customization just one time, you can type the command and switch in the Run dialog box (Start menu) in Microsoft Windows. If you want to use a particular switch many times or every time that you start the app, you can create a desktop shortcut that starts the program by using the same switch and parameters. This article describes how to do both. It also includes a table that lists all of the switches and parameters that are available in the desktop Office apps.

Using a command-line switch doesn’t mean you have to type the whole startup command at the command prompt. You can start the Office app as usual, by clicking the program icon on the desktop, or by clicking the program name on the Start menu. All startup methods essentially do the same thing: they run the app’s .exe file, even if you don’t actually type the command or even see it.

A command-line switch is a modifier that is added to the .exe file. A startup file with a switch looks like this.

 outlook.exe /nopreview

In this example, a command-line switch has been added to the .exe file for Microsoft Outlook. The switch consists of a forward slash and a word or abbreviation that indicates the switch’s action. This switch tells Outlook to launch without showing the Reading Pane.

A switch is sometimes followed by one or more specific instructions called parameters, which give the program further information about how to run the .exe command. For example, the following command tells Outlook to load a specific profile name upon startup.

outlook exe /profile profilename

Switch names cannot be abbreviated and are not case-sensitive. However, their parameters are sometimes case-sensitive.

Here are the names of the startup commands for the Office products Word, Excel, PowerPoint, PowerPoint viewer, Outlook, and Access.

Word

winword.exe

Excel

excel.exe

PowerPoint

powerpnt.exe

PowerPoint Viewer

pptview.exe

Outlook

outlook.exe

Access

msaccess.exe

When you use one of the Office startup commands, you must supply the full path to the product’s .exe file. Verify the location of this file on your computer. This table shows the locations of the .exe files if you accepted the default folder locations during installation.

In Office 2007

Windows 32-bit: C:Program Files (x86)Microsoft OfficeOffice12

Windows 64-bit: C:Program FilesMicrosoft OfficeOffice12

In Office 2010

Windows 32-bit: C:Program Files (x86)Microsoft OfficeOffice14

Windows 64-bit: C:Program FilesMicrosoft OfficeOffice14

In Office 2013

Windows 32-bit: C:Program Files (x86)Microsoft OfficeOffice15

Windows 64-bit: C:Program FilesMicrosoft OfficeOffice15

In Office 2016 
& Office 2019

Windows 32-bit: C:Program Files (x86)Microsoft OfficeOffice16

Windows 64-bit: C:Program FilesMicrosoft OfficeOffice16

In Office 365

Windows 32-bit: C:Program Files (x86)Microsoft OfficerootOffice16

Windows 64-bit: C:Program FilesMicrosoft OfficerootOffice16

  1. In Windows 10, click the Search or Cortana icon in the taskbar, type Run, and then click Command Prompt in the results.

    In Windows 8, press the Windows key, type Run, and then press Enter.

    In Windows 7, click Start, point to All Programs, click Accessories, and then click Run.

  2. In the Run dialog box, type a quotation mark, enter the full path for the app’s .exe file, and then type another quotation mark. Alternatively, click Browse to locate and select the file. In this case, the quotation marks are supplied automatically.

  3. After the closing quotation mark, type a space, and then type the switch. For example, you might type:

    "c:program filesmicrosoft officeoffice15outlook.exe" /nopreview
    

The next time you start the app, it opens as usual. To make your customized startup available for repeated uses, see the next section.

Note the following about using command-line switches:

  • You can use only one switch at a time. Starting an Office app with multiple switches is not supported.

  • If the parameter is a path to a location on your computer, or a file name with spaces in it, enclose it in double quotation marks—for example, /t «Monthly Report.dotx».

  • Switches and parameters are not case-sensitive. For example, /RO functions the same as /ro.

  • Include one blank space before each switch and one before each parameter.

  1. Right-click the Windows desktop, point to New, and then click Shortcut on the shortcut menu.

  2. In the Create Shortcut Wizard, in the Type the location of the item box, type a double quotation mark («), enter the full path for the app’s .exe file (including the file name), and then type another double quotation mark. (Alternatively, click Browse to locate and select the file. In this case, the quotation marks are added automatically.)

  3. Following the closing quotation mark, type a space, and then type the switch and any parameters. If the parameter is a path to a location on your computer, and the path contains a space, it also must be enclosed in quotation marks. For example:

    "c:program filesmicrosoft officeoffice15excel.exe" /r "c:My Folderbook1.xlsx"
    

  4. Click Next.

  5. In the Type a name for this shortcut box, type a name for the shortcut, and then click Finish.

    The wizard creates the shortcut and places it on the desktop.

Whenever you want to use the shortcut to start the app, double-click it.

To add the desktop shortcut to the Windows Start menu, right-click the shortcut, and then click Pin to Start menu on the shortcut menu.

List of command-line switches for Office products

Each Office product has a different set of command-line switches.

Note: These lists don’t include all switches added since Office 2007. If you use command-line switches and want information about newer switches that are available, please respond Yes or No to the «Was this information helpful» question at the end of this topic. Then, in the box that appears, tell us which Office product and version you’re interested in.

Switch and parameter

Description

/safe

Starts Word in Safe Mode.

/q

Starts Word without displaying the Word splash screen.

/ttemplatename

Starts Word with a new document based on a template other than the Normal template.

Example    To start Word with a document based on a template called Myfax.dotx, stored on the C drive, type the following at the command prompt:

/tc:Myfax.dotx

Note: Do not include a space between the switch and the name of the template file.

Security Note: Because templates can store macro viruses, be careful about opening them or creating files based on new templates. Take the following precautions: run up-to-date antivirus software on your computer, set your macro security level to high, clear the Trust all installed add-ins and templates check box, use digital signatures, and maintain a list of trusted sources.

/t filename

Starts Word and opens an existing file.

Example    To start Word and open the template file Myfax.dotx, stored on the C drive, type the following at the command prompt:

/t c:Myfax.dotx

Example    To start Word and open multiple files, such as MyFile.docx and MyFile2.docx, each stored on the C drive, type the following at the command prompt:

/t c:MyFile.docx c:MyFile2.docx

/f filename

Starts Word with a new document based on an existing file.

Example    To start Word and create a new document based on file MyFile.docx, stored on the desktop, type the following at the command prompt:

/f «c:Documents and SettingsAll UsersDesktopMyFile.docx»

/h http://filename

Starts Word and opens a read-only copy of a document that is stored on a Microsoft Windows SharePoint Services site. The site must be on a computer that is running Word 2007 or later or Windows SharePoint Services 2.0 or later.

Example    To start Word and open a copy of file MyFile.docx, stored in a document library at the URL http://MySite/Documents, type the following at the command prompt:

/h http://MySite/Documents/MyFile.docx

Note: If the document is checked out to you, the /h switch has no effect. Word opens the file so that you can edit it.

/pxslt

Starts Word and opens an existing XML document based on the specified Extensible Stylesheet Language Transformation (XSLT).

Example    To start Word and apply the XSLT MyTransform, stored on the C drive, to the XML file Data.xml, also stored on the C drive, type the following at the command prompt:

/pc:MyTransform.xsl c:Data.xml

/a

Starts Word and prevents add-ins and global templates (including the Normal template) from being loaded automatically. The /a switch also locks the setting files.

/ladd-in

Starts Word and then loads a specific Word add-in.

Example    To start Word and then load the add-in Sales.dll, stored on the C drive, type the following at the command prompt:

/lc:Sales.dll

Note: Do not include a space between the switch and the add-in name.

Security Note: Use caution when running executable files or code in macros or applications. Executable files or code can be used to carry out actions that might compromise the security of your computer and data.

/m

Starts Word without running any AutoExec macros.

/mmacroname

Starts Word and then runs a specific macro. The /m switch also prevents Word from running any AutoExec macros.

Example    To start Word and then run the macro Salelead, type the following at the command prompt:

/mSalelead

Note: Do not include a space between the switch and the macro name.

Because macros can contain viruses, be careful about running them. Take the following precautions: run up-to-date antivirus software on your computer; set your macro security level to high; clear the Trust all installed add-ins and templates check box; use digital signatures; maintain a list of trusted publishers.

/n

Starts a new instance of Word with no document open. Documents opened in each instance of Word will not appear as choices in the Switch Windows list of other instances.

/w

Starts a new instance of Word with a blank document. Documents opened in each instance of Word will not appear as choices in the Switch Windows list of the other instances.

/r

Re-registers Word in the Windows registry. This switch starts Word, runs Office Setup, updates the Windows registry, and then closes.

/x

Starts Word from the operating system shell so that Word responds to only one Dynamic Data Exchange (DDE) request (for example, to print a document programmatically).

/ztemplatename

Visibly behaves exactly like the /t switch. However, you can use the /z switch with Word to generate both a Startup and a New event, whereas the /t switch generates only a Startup event.

Switch and parameter

Description

workbook path | file name

This parameter does not require a switch.

Starts Excel and opens the specified file.

Example

excel.exe «c:My Folderbook1.xlsx»

or

excel.exe http://MySite/Book1.xlsx

/r
workbook path | file name

Opens a specific workbook as read-only.

Example

excel.exe /r «c:My Folderbook1.xlsx»

or

excel.exe /r http://MySite/Book1.xlsx

/t
workbook path | file name

Starts Excel and opens the specified file as a template.

Example

excel.exe /t «c:My Folderbook_name.xlsx».

or

excel.exe /t http://MySite/book_name.xlsx

/n
workbook path | file name

Like /t, starts Excel and opens the specified file as a template.

Example

excel.exe /n «c:My Folderbook_name.xlsx».

or

excel.exe /n http://MySite/book_name.xlsx

/e or /embed

Prevents the Excel startup screen from appearing and a new blank workbook from opening.

Example

excel.exe /e

/p
workbook path

Specifies a folder as the active working folder (for example, the folder that is pointed to in the Save As dialog box).

Example

excel.exe /p «c:My Folder»

/s or /safemode

Forces Excel to bypass all files that are stored in startup directories, such as the default XLStart folder located in the directory where Excel or Microsoft Office is installed.

Example

excel.exe /s

/m

Creates a new workbook that contains a single XLM macro sheet.

Example

excel.exe /m

/a
progID

Starts Excel and loads the Automation add-in that is specified by the progID of the add-in.

Example

excel.exe /a MyProgId.MyProgID2.1

/x

Starts a new instance (a separate process) of Excel.

Example

excel.exe /x «c:My Folderbook1.xlsx»

or

excel.exe /x http://MySite/Book1.xlsx

Here are the command-line switches that are available for PowerPoint.

Switch or parameter

Action

/B

Starts PowerPoint with a new blank presentation.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /B

/C

Starts PowerPoint with the specified file open and also starts Microsoft Windows NetMeeting conferencing.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /C NetMeetingPresentation.pptx

Note: If you use this switch without specifying a file, PowerPoint starts with no presentation open and NetMeeting conferencing is not started.

/EMBEDDING

Starts PowerPoint without displaying the Office PowerPoint 2007 program window. Developers use this switch when testing add-ins.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /EMBEDDING

/M MACRO

Runs a macro in a specified presentation.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /M myfile.pptm «MyMacro»

«MyMacro» is a macro in the file myfile.pptm.

/N

Starts PowerPoint and creates a new presentation.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /N «Pathtemplatename.potx»

This example specifies the name of the template that the new presentation is based on: templatename.potx.

If a template name is not supplied, PowerPoint starts a new presentation based on the blank template (in effect, the same as using the /N switch without a template name).

/O

Starts PowerPoint and specifies a list of files to open.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /O File name1.pptx, File name2.pptx

/P

Prints the presentation to the default printer by using default settings.

When you use the /P switch, PowerPoint displays the Print dialog box before printing. After you choose options and click OK, the dialog box closes, and PowerPoint prints the file and then closes. If you don’t want to see PowerPoint at all, use the /PT (Print To) switch instead.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /P «MyFile.pptx»

/PT

Prints the presentation to the specified printer by using the default settings.

If you don’t want to see PowerPoint at all, use the /PT (Print To) switch.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /PT «PrinterName» «» «» «MyFile.pptx»

PrinterName is the name of the printer that appears in the Name box under Printer in the Print dialog box. The empty quotation marks are necessary; the quotation marks around PrinterName and the path to the PPTX file are needed only if there are spaces in either of the names, but it is always a good idea to use them.

/PWO

Prints the specified file, but show the Print dialog box.

When you use the /P switch, PowerPoint displays the Print dialog box before printing. After you choose options and click OK, the dialog box closes, and PowerPoint prints the file and then closes. If you don’t want to see PowerPoint at all, use the /PT (Print To) switch instead.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /PWO «MyFile.pptx»

/RESTORE

Restores PowerPoint to the way it was before the program closed abnormally. When PowerPoint restarts, it will attempt to recover and restore some aspects of the state of the program and presentations before it closed.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /RESTORE

/S

Opens the specified presentation file as a slide show.

Example: «c:program filesmicrosoft officeoffice12POWERPNT.exe» /S «Presentation1.pptx»

Here are the command-line switches that are available for PowerPoint Viewer.

Switch or parameter

Action

/D

Shows the Open dialog box when the presentation ends.

Example: «c:program filesmicrosoft officeoffice12PPTVIEW.exe» /D

/L

Reads a playlist of PowerPoint presentations contained within a text file.

Example: «c:program filesmicrosoft officeoffice12PPTVIEW.exe» /L «Your_Play_List.txt «

Note: The playlist file is a list of presentation file names (preceded by the path as needed). It is not possible to add additional command-line switches to the individual presentations within the playlist.

/N#

Opens the presentation at a specified slide number, instead of slide 1.

Example: «c:program filesmicrosoft officeoffice12PPTVIEW.exe» /N5 «Presentation.pptx»

This example opens Presentation.pptx at slide 5.

/S

Starts the viewer without showing the splash screen.

Example: «c:program filesmicrosoft officeoffice12PPTVIEW.exe» /S

/P

Sends the presentation to a printer, and print the file.

Example: «c:program filesmicrosoft officeoffice12PPTVIEW.exe» /P «Presentation.pptx»

This example prints the Presentation.pptx file.

Switch

Description

/a

Creates an item with the specified file as an attachment.

Example:

  • «c:program filesmicrosoft officeoffice15outlook.exe» /a «c:my documentslabels.doc»

If no item type is specified, IPM.Note is assumed. Cannot be used with message classes that are not based on Outlook.

/altvba otmfilename

Opens the VBA program specified in otmfilename, instead of %appdata%microsoftoutlookvbaproject.otm.

/c messageclass

Creates a new item of the specified message class (Outlook forms or any other valid MAPI form).

Examples:

  • /c ipm.activity creates a Journal entry

  • /c ipm.appointment creates an appointment

  • /c ipm.contact creates a contact

  • /c ipm.note creates an e-mail message

  • /c ipm.stickynote creates a note

  • /c ipm.task creates a task

/checkclient

Prompts for the default manager of e-mail, news, and contacts.

/cleanautocompletecache

Removes all names and e-mail addresses from the Auto-Complete list. (Outlook 2013, 2016 only)

/cleancategories

Deletes any custom category names that you have created. Restores categories to the default names.

/cleanclientrules

Starts Outlook and deletes client-based rules.

/cleanconvongoingactions

Deletes the Conversations Actions Table (CAT). CAT entries for a conversation thread usually expire 30 days after no activity. The command-line switch clears all conversation tagging, ignore, and moving rules immediately stopping any additional actions. (Outlook 2013, 2016 only)

/cleandmrecords

Deletes the logging records saved when a manager or a delegate declines a meeting.

/cleanfinders

Resets all Search Folders in the Microsoft Exchange mailbox for only the first profile opened.

/cleanfromaddresses

Removes all manually added From entries from the profile.

/cleanmailtipcache

Removes all MailTips from the cache. (Outlook 2013, 2016 only)

/cleanreminders

Clears and regenerates reminders.

/cleanroamedprefs

All previous roamed preferences are deleted and copied again from the local settings on the computer where this switch is used. This includes the roaming settings for reminders, free/busy grid, working hours, calendar publishing, and RSS rules.

/cleanrules

Starts Outlook and deletes client-based and server-based rules.


Important
If you have multiple or additional mailboxes in your Outlook profile, running the /cleanrules command line switch deletes the rules from all connected mailboxes. Therefore, it is recommended that you only run this command when your Outlook profile only contains the one, target mailbox.

/cleanserverrules

Starts Outlook and deletes server-based rules.

/cleansharing

Removes all RSS, Internet Calendar, and SharePoint subscriptions from Account Settings, but leaves all the previously downloaded content on your computer. This is useful if you cannot delete one of these subscriptions within Outlook 2013.

/cleansniff

Overrides the programmatic lockout that determines which of your computers (when you run Outlook at the same time) processes meeting items. The lockout process helps prevent duplicate reminder messages. This switch clears the lockout on the computer it is used. This enables Outlook to process meeting items.

/cleansubscriptions

Deletes the subscription messages and properties for subscription features.

/cleanweather

Removes city locations added to the Weather Bar.

/cleanviews

Restores default views. All custom views you created are lost.

/embedding

Used without command-line parameters for standard OLE co-create.

/f msgfilename

Opens the specified message file (.msg) or Microsoft Office saved search (.oss).

/finder

Opens the Advanced Find dialog box.

/hol holfilename

Opens the specified .hol file.

/ical icsfilename

Opens the specified .ics file.

/importNK2

Imports the contents of an .nk2 file which contains the nickname list used by both the automatic name checking and Auto-Complete features.

/importprf prffilename

Starts Outlook and opens/imports the defined MAPI profile (*.prf). If Outlook is already open, queues the profile to be imported on the next clean start.

/launchtraininghelp assetid

Opens a Help window with the Help topic specified in assetid displayed.

/m emailname

Provides a way for the user to add an e-mail name to the item. Only works together with the /c command-line parameter.

Examples:

  • Outlook.exe /c ipm.note /m emailname

  • Outlook.exe /c ipm.note /m user@contoso.com?subject=Test&body=Hello

/noextensions

Both native and managed Component Object Model (COM) add-ins are turned off.

/nopreview

Starts Outlook with the Reading Pane off.

/p msgfilename

Prints the specified message (.msg).

/profile profilename

Loads the specified profile. If your profile name contains a space, enclose the profile name in quotation marks (» «).

/profiles

Opens the Choose Profile dialog box regardless of the Options setting on the Tools menu.

/promptimportprf

Same as /importprf except a prompt appears and the user can cancel the import.

/recycle

Starts Outlook by using an existing Outlook window, if one exists. Used in combination with /explorer or /folder.

/remigratecategories

Starts Outlook and starts the following commands on the default mailbox:

  • Upgrades colored For Follow Up flags to Outlook 2013 color categories.

  • Upgrades calendar labels to Outlook 2013 color categories.

  • Adds all categories used on non-mail items into the Master Category List

Note: This is the same command as Upgrade to Color Categories in each Outlook mailbox properties dialog box.

/resetfolders

Restores missing folders at the default delivery location.

/resetfoldernames

Resets default folder names (such as Inbox or Sent Items) to default names in the current Office user interface language.

For example, if you first connect to your mailbox in Outlook by using a Russian user interface, the Russian default folder names cannot be renamed. To change the default folder names to another language, such as Japanese or English, you can use this switch to reset the default folder names after you change the user interface language or install a different language version of Outlook.

/resetformregions

Empties the form regions cache and reloads the form region definitions from the Windows registry.

/resetnavpane

Clears and regenerates the Folder Pane for the current profile.

/resetquicksteps

Restores the default Quick Steps. All user-created Quick Steps are deleted.

/resetsearchcriteria

Resets all Instant Search criteria so the default set of criteria is shown in each module.

/resetsharedfolders

Removes all shared folders from the Folder Pane.

/resettodobar

Clears and regenerates the To-Do Bar task list for the current profile.

/restore

Attempts to open the same profile and folders that were open prior to an abnormal Outlook shutdown. (Outlook 2013, 2016 only)

/rpcdiag

Opens Outlook and displays the remote procedure call (RPC) connection status dialog box.

/safe

Starts Outlook without the Reading Pane or toolbar customizations. Both native and managed Component Object Model (COM) add-ins are turned off.

/safe:1

Starts Outlook with the Reading Pane off.

/safe:3

Both native and managed Component Object Model (COM) add-ins are turned off.

/select foldername

Starts Outlook and opens the specified folder in a new window. For example, to open Outlook and display the default calendar, use: «c:program filesmicrosoft officeoffice15outlook.exe» /select outlook:calendar.

/share feed://URL/filename

/share stssync://URL

/share web://URL/filename

Specifies a sharing URL to connect to Outlook. For example, use stssync://URL to connect a SharePoint list to Outlook.

/sniff

Starts Outlook, forces a detection of new meeting requests in the Inbox, and then adds them to the calendar.

/t oftfilename

Opens the specified .oft file.

/v vcffilename

Opens the specified .vcf file.

/vcal vcsfilename

Opens the specified .vcs file.

Switch

Parameter

Description

None

database

Opens the specified database or Microsoft Access project. You can include a path, if necessary. If the path contains spaces, enclose it in quotation marks.

/excl

None

Opens the specified Access database for exclusive access. To open the database for shared use in a multiuser environment, omit this switch. Applies to Access databases only.

/
ro

None

Opens the specified Access database or Access project for read-only use.

/runtime

None

Specifies that Access will start with runtime version options.

/profile

user profile

Starts Access by using the options in the specified user profile instead of the standard Windows Registry settings created when you installed Access. This replaces the /ini switch used in versions of Access prior to Access 95 to specify an initialization file.

/compact

target database or target Access project

Compacts and repairs the Access database, or compacts the Access project that was specified before the /compact switch, and then closes Access. If you omit a target file name following the /compact switch, the file is compacted to the original name and folder. To compact to a different name, specify a target file. If you include a path that contains spaces, enclose the path in quotation marks.

If you specify a file name in the target database or target Access project parameter but you don’t include a path, the target file is created in the default database folder that is specified in Access. You can change this setting in the Access Options dialog box.

In an Access project, this option compacts the Access project (.adp) file but not the Microsoft SQL Server database.

/x

macro

Opens the Access database that was specified before the /x switch, and then runs the specified macro. Another way to run a macro when you open a database is to create a macro named AutoExec.

Macros can contain viruses, so you must be careful about running them. Take the following precautions: run up-to-date antivirus software on your computer; use the Trust Center to disable all macros except those that are digitally signed; maintain a list of trusted sources of macros.

/
cmd

None

Specifies that what follows on the command line is the value that will be returned by the Command function. This option must be the last switch on the command line. You can use a semicolon (;) as an alternative to /cmd.

Use this switch to specify a command-line argument that can be used in Visual Basic for Applications (VBA) code.

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

word logo

Like most apps, you can launch Word from the Command Prompt, but Word also supports several optional switches for controlling the startup process.

Whether you type the command at the prompt, use it to create a shortcut, insert it as part of a batch script, launching Word with additional parameters lets you do things like start Word in Safe Mode for troubleshooting or start with a specific template.

Before we can open Word using the Command Prompt, we need to figure out which directory the winword.exe file is located. You can do this manually, or you can just have the Command Prompt find it for you. To do this, go ahead and open the Command Prompt by opening the start menu and typing “cmd” and selecting the “Command Prompt” application.

Open Command Prompt in Start Menu

When you open the Command Prompt, you’ll be in the top tier directory—your user account folder. We need to dig deeper by going into the Program Files directory. Do so by entering the following command and then pressing Enter:

cd”program files (x86)”

Program Files in Command Prompt

You’ll now be in the Program Files directory. The next step is to locate the directory where the winword.exe file is located. Do so by typing the following command and pressing “Enter.”

dir winword.exe /s

Once you enter this command, the Command Prompt will locate the directory for you.

Winword directory

Now that you know the directory where the winword.exe file is located, you can use the cd command to open the file path. In this example, you would need to enter the following command:

cd Microsoft OfficerootOffice16

Now you should be in the directory where winword.exe is located.

Open Winword file

Now, if you want to open Microsoft Word the same way as if you were opening it via its icon, all you must do is type winword and then press “Enter,” and Word will open its usual way.

Open Normal Word

However, the whole point of using the command is that you can use the different switches and parameters it offers.

Common Word Command Line Switches and Parameters

Borrowed from the official Microsoft Office support site, here is a list of some possible ways to open Word, along with its respective command.

Switch and Parameter Description
/safe Starts Word in Safe Mode. This launches Word without any additional add-ins, templates, and other customizations. It’s helpful when troubleshooting problems in Word.

You can also launch Word in Safe Mode by holding down the Ctrl key while launching Word from the Start menu, creating a shortcut with this parameter makes it that much easier.

/q Starts Word without displaying the Word Splash screen.
/ttemplatename Starts Word with a new document based on a template other than the Normal template.

Example: Assume we wanted to open a document stored on the C drive called example.docx, we’d type the following command:

/tc:example.docx

Note: Do not put a space between the switch and the name of the file.

/t filename Starts Word and opens an existing file.

Example: To start Word and open the existing file example.docx, stored on the C drive, enter the following:

/t c:example.docx

To open multiple files, example.docx and example2.docx, located in the C drive at once, enter the following:

/t c:example.docx c:example2.docx

/f filename Starts Word with a new document based on an existing file.

Example: To start Word and create a new document based on file example.docx, stored on the desktop, enter the following:

/f “c:Documents and SettingsAll UsersDesktopexample.docx

/h http://filename Starts Word and opens a read-only copy of a document that is stored on a Microsoft Windows SharePoint Services site. The site must be on a computer that is running Word 2007 or later or Windows SharePoint Services 2.0 or later.

Example: To start Word and open a copy of a file example.docx, stored in a document library at the URL http://MySite/Documents, enter the following:

/h http://MySite/Documents/example.docx

Note: If the document is checked out to you, the /h switch has no effect. Word opens the files so that you can edit it.

/pxslt Starts Word and opens an existing XML document based on the specified XSLT.

Example: To start and apply the XSLT MyTransform, stored on the C drive, enter the following:

/pc:MyTransform.xsl c:Data.sml

/a Starts Word and prevents add-ins and global templates (including the Normal template) from being loaded automatically. The /a switch also locks the settings files.
/ladd-in Starts Word and then loads a specific Word add-in.

Example: To start Word and load the add-in Sales.dll, stored on the C drive, enter the following:

/ic:Sales.dll

Note: Do not include a space between the switch and the add-in name.

/m Starts Word without running any AutoExec macros.
/mmacroname Starts Word and the runs a specific macro. The m/ switch also prevents word from running any AutoExec macros.

Example: To start Word and then run the macro Salelead, enter the following:

/mSalelead

Note: Do not include a space between the switch and the macro name.

/n Starts a new instance of Word with no document open. Documents opened in each instance of Word will not appear as choices in the Switch Windows list of other instances.
/w Starts a new instance of Word with a blank document. Documents opened in each instance of Word will not appear as choices in the Switch Windows list of other instances.
/r Re-register Word in the Windows registry. This switch starts Word, runs Office Setup, updates the Windows registry, and the closes.
/x Starts Word from the operating system shell so that Word responds to only one DDE request (for example, to print a document programmatically).
/ztemplatename Visibly behaves exactly like the /t switch. However, you can use the /z switch with Word to generate both a Startup and a New event, whereas the /t switch generates only a Startup event.

That’s all there is to it! Now you should be able to open Word in any specific way you choose by simply following these commands.

RELATED: How to Run Command Prompt Commands from a Windows Shortcut

READ NEXT

  • › How to Turn Off Dark Mode in Microsoft Word
  • › How to Link or Embed a PowerPoint Slide in a Word Document
  • › How to Turn Off Track Changes in Word
  • › How (and Why) to Start Microsoft PowerPoint from the Command Prompt
  • › How to Put Borders Around Images in Microsoft Word
  • › How to Insert an Image Inside of Text in Microsoft Word
  • › How (and Why) to Start Microsoft Excel from the Command Prompt
  • › Why ChatGPT Is Not a Replacement for Siri and Google Assistant

How-To Geek is where you turn when you want experts to explain technology. Since we launched in 2006, our articles have been read billions of times. Want to know more?

Microsoft Word

Статья создана 28.03.2020

При запуске продукта Microsoft Office его загрузка выполняется в стандартном режиме. Microsoft Word, например, отображает экран-заставку Word и загружает шаблон «Обычный». Однако предположим, что вы хотите запустить Word без экрана-заставки, а затем загрузить другой шаблон. Кроме того, вам может потребоваться загрузить надстройку, запустив макрос. Для этого можно добавить подкоманды (которые называются переключателями командной строки) в команду запуска приложения Office.

Если вы хотите использовать такие настройки всего один раз, вы можете ввести команду и переключатель в диалоговом окне Выполнить (меню «Пуск») в Microsoft Windows. Если же нужно использовать один и тот же переключатель несколько раз или каждый раз при запуске приложения, можно создать на рабочем столе ярлык, с помощью которого вы сможете запускать программу, используя одни и те же переключатели и параметры. В этой статье описаны оба этих метода, а также приведена таблица, содержащая все переключатели и параметры, доступные для классических приложений Office.

Сведения о командах, ключах и параметрах для Microsoft Word

Для использования кюча (переключателя) вовсе не нужно вводить всю команду запуска в командной строке. Вы можете запустить приложение Office как обычно, щелкнув значок на рабочем столе или название программы в меню Пуск. Все способы запуска фактически делают одно и то же: они запускают EXE-файл приложения, даже если вы не вводите саму команду или не видите ее.

Ключ (переключатель) командной строки представляет собой модификатор, который добавляется к EXE-файлу. Файл загрузки с переключателем выглядит следующим образом:

outlook.exe /nopreview

В этом примере переключатель командной строки добавлен к EXE-файлу Microsoft Outlook. Он включает в себя косую черту и слово или аббревиатуру, которые указывают на его действие. Данный переключатель позволяет отключить область чтения в Outlook.

Иногда за переключателем следуют отдельные инструкции, которые называются параметрами. Они предоставляют программе дополнительные сведения о том, как следует выполнять команду. Например, следующая команда позволяет загрузить определенный профиль при запуске Outlook:

outlook exe /profile profilename

Имена переключателей нельзя сокращать, но в них не учитывается регистр. Однако параметры иногда вводятся с учетом регистра.

Команды запуска и пути к Microsoft Office

Word — winword.exe

Excel — excel.exe

PowerPoint — powerpnt.exe

PowerPoint — pptview.exe

Outlook — outlook.exe

Access — msaccess.exe

ри использовании одной из команд запуска Office необходимо указать полный путь к EXE-файлу продукта. Прежде всего определите расположение файла. В этой таблице указано, где находятся EXE-файлы, если при установке вы решили использовать стандартные папки.

В Office 2007

32-разрядный выпуск Windows: C:Program FilesMicrosoft OfficeOffice12
64-разрядный выпуск Windows: C:Program Files (x86)Microsoft OfficeOffice12

В Office 2010

32-разрядный выпуск Windows: C:Program FilesMicrosoft OfficeOffice14
64-разрядный выпуск Windows: C:Program Files (x86)Microsoft OfficeOffice14

В Office 2013

32-разрядный выпуск Windows: C:Program FilesMicrosoft OfficeOffice15
64-разрядный выпуск Windows: C:Program Files (x86)Microsoft OfficeOffice15

В Office 2016

32-разрядный выпуск Windows: C:Program FilesMicrosoft OfficeOffice16
64-разрядный выпуск Windows: C:Program Files (x86)Microsoft OfficeOffice16

Однократное использование переключателя путем его добавления к команде «Выполнить»

a. В Windows 10 щелкните значок поиска или Кортаны на панели задач, введите Выполнить и щелкните Командная строка в результатах поиска.

На компьютере с Windows 8 нажмите клавишу Windows, введите команду Выполнить и нажмите клавишу ВВОД.

В Windows 7 нажмите кнопку Пуск и выберите пункты Все программы, Стандартные, Выполнить.

b. В диалоговом окне Выполнить введите прямые кавычки и внутри них укажите полный путь к EXE-файлу приложения или нажмите кнопку Обзор для поиска данного файла. В этом случае кавычки подставляются автоматически.

c. После закрывающей кавычки введите пробел, а затем переключатель, например:

«c:program filesmicrosoft officeoffice15outlook.exe» /nopreview

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

Ограничения переключателей командной строки для Microsoft Word

Одновременно можно использовать только один переключатель. Запуск приложения Office с несколькими переключателями не поддерживается.

Если параметром является путь к расположению на вашем компьютере или имя файла с пробелами, заключите его в двойные кавычки (например, вот так: /t «Ежемесячный отчет.dotx»).

В переключателях и параметрах регистр не учитывается. Например, «/RO» работает так же, как «/ro».

Не забывайте вводить пробел перед каждым переключателем и параметром.

Параметр

Описание

/safe

Запуск Word в безопасном режиме.

/q

Запуск Word без вывода экрана-заставки.

/ttemplatename

Запуск Word с новым документом, который основан не на шаблоне — обычный.

Пример: Чтобы запустить Word с документом, который основан на шаблоне Myfax.dotx, хранящемся на диске C, введите следующую команду:

/tc:Myfax.dotx

Примечание: Не добавляйте пробел между переключателем и именем файла шаблона.

/t filename

Запуск Word и открытие существующего файла.

Пример Чтобы запустить Word и открыть шаблон Myfax.dotx, хранящийся на диске C, введите следующую команду:

/t c:Myfax.dotx

Пример Чтобы запустить Word и открыть несколько файлов, например шаблоны MyFile.docx и MyFile2.docx, хранящиеся на диске C, введите следующую команду:

/t c:MyFile.docx c:MyFile2.docx

/h http://filename

Запуск Word и открытие предназначенной только для чтения копии документа, который хранится на сайте Microsoft Windows SharePoint Services. Сайт должен размещаться на компьютере с Word 2007 или более поздней версии и Windows SharePoint Services 2.0 или более поздней версии.

Пример Чтобы запустить Word и открыть копию файла MyFile.docx, хранящегося в библиотеке документов по URL-адресу http://MySite/Documents, введите следующую команду:

/h http://MySite/Documents/MyFile.docx

/pxslt

Запуск Word и открытие существующего XML-документа, основанного на указанном преобразовании Запуск Word и открытие существующего XML-документа, основанного на указанном преобразовании Запуск Word и открытие существующего XML-документа, основанного на указанном преобразовании XSLT.

Пример Чтобы запустить Word и применить преобразование XSLT MyTransform, хранящееся на диске C, к XML-файлу Data.xml, также хранящемуся на диске C, введите следующую команду:

/pc:MyTransform.xsl c:Data.xml

/a

Запуск Word и предотвращение автоматической загрузки надстроек и глобальных шаблонов (включая шаблон «Обычный»). Переключатель /a также блокирует файлы параметров.

/ladd-in

Запуск Word и загрузка определенной надстройки.

Пример. Чтобы запустить Word и загрузить надстройку Sales.dll, хранящуюся на диске C, введите следующую команду:

/lc:Sales.dll

/m

Запуск Word без выполнения макросов AutoExec.

/mmacroname

Запуск Word и выполнение определенного макроса. Переключатель /m также запрещает запуск <>макросов AutoExec.

Пример. Чтобы запустить Word и выполнить макрос Salelead, введите следующую команду:

/mSalelead

/n

Запуск нового экземпляра Word без открытия документа. Документы, открытые в экземпляре Word, не будут отображаться в списке Перейти в другое окно других экземпляров.

/w

Запуск нового экземпляра Word с пустым документом. Документы, открытые в экземпляре Word, не будут отображаться в списке Перейти в другое окно других экземпляров.

/r

Повторная регистрация Word в реестре Windows. Этот переключатель запускает Word, вызывает мастер установки Office, обновляет реестр Windows, а затем закрывает мастер.

/x

Запуск Word из оболочки операционной системы. При этом Word отвечает только на один запрос динамического обмена данными (DDE) (например, для печати документа программным путем).

Примечание

Не добавляйте пробел между переключателем и именем файла шаблона.

Если документ извлечен вами, переключатель /h не действует. Файл открывается в Word, и вы можете изменить его.

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

Так как макросы могут содержать вирусы, соблюдайте осторожность при их запуске. Используйте следующие меры предосторожности: обновляйте антивирусную программу; задайте для макросов высокий уровень безопасности; снимите флажок Доверять всем установленным надстройкам и шаблонам; используйте цифровые подписи; ведите список надежных издателей.

Источник

Microsoft.com

Как и большинство приложений, вы можете запускать Word из командной строки. Однако Word также поддерживает некоторые дополнительные переключатели для управления процессом загрузки. Запуск Word с дополнительными параметрами позволяет выполнять такие действия, как запуск Word в безопасном режиме для устранения неполадок или запускать с помощью определенного шаблона.

  1. Процедура открытия Microsoft Office 2013/2016 в безопасном режиме
  2. Советы по чтению файлов Word, не открывая их
  3. Сводка распространенных сочетаний клавиш Microsoft Word

Прежде чем использовать командную строку для открытия Word, нам нужно найти папку, содержащую файл winword.exe. Вы можете выполнять поиск вручную или использовать командную строку. Чтобы найти папку с помощью CMD, откройте командную строку в меню «Пуск», набрав cmd и выбрав соответствующий результат.

Изображение 1: Как открыть Microsoft Word из командной строки

Когда откроется командная строка, вы увидите папку учетной записи пользователя. Чтобы найти файл winword.exe, вам нужно углубиться в каталог Program Files, введя следующую команду и нажав Enter:

cd’программные файлы (x86) ‘

Изображение 2: Как открыть Microsoft Word из командной строки

Теперь вы окажетесь в папке Program Files. Следующим шагом будет определение папки, содержащей файл winword.exe, введя следующую команду и нажав Enter.

каталог winword.exe / s

Когда вы вводите эту команду, командная строка сама найдет каталог.

Изображение 3: Как открыть Microsoft Word из командной строки

Узнав каталог, в котором находится файл winword.exe, вы можете использовать команду cd, чтобы открыть путь к файлу. В этом примере вам нужно ввести следующую команду:

компакт-диск Microsoft OfficerootOffice16

Вы попадете в папку, содержащую файл winword.exe.

Изображение 4: Как открыть Microsoft Word из командной строки

Параметры и переключатель командной строки Word common

Ниже приведен список некоторых способов открыть Word вместе с соответствующей командой.

  1. / safe: открыть Word в безопасном режиме. Это означает, что Word открывается без надстроек, шаблонов и других параметров. Это полезно при устранении неполадок в Word.

Вы также можете запустить Word в безопасном режиме, удерживая клавишу Ctrl при запуске Word из меню «Пуск», создавая ярлыки с этим параметром для облегчения доступа.

  1. / q: открыть Word без отображения экрана-заставки Word.
  2. / ttemplatename: открыть Word с новым документом, основанным на другом шаблоне с обычным шаблоном.

Пример: Предположим, вы хотите открыть документ, хранящийся на диске C, с именем example.docx, введите следующую команду:

/tc:example.docx

Примечание. Не устанавливайте пробел между переключателем и именем файла.

  1. / t имя файла: запустить Word и открыть существующий файл.

Например: чтобы запустить Word и открыть файл example.docx, хранящийся на диске C, введите следующую команду:

/tc:example.docx

Чтобы открыть несколько файлов example.docx и example2.docx, находящихся на диске C одновременно, введите следующее:

/tc:example.docx c: example2.docx

  1. / f имя файла: запустить Word с новым документом на основе существующего файла.

Например: чтобы запустить Word и создать новый документ на основе файла example.docx, хранящегося на рабочем столе, введите следующее:

/ f ‘c: Documents and SettingsAll UsersDesktopexample.docx

  1. / h http: /// filename: Запустите Word и откройте доступную только для чтения копию, хранящуюся на странице Microsoft Windows SharePoint Services, на компьютере, на котором работает Word 2007 или более поздняя версия или Windows SharePoint Services 2.0 или более поздняя версия.

Например: чтобы запустить Word и открыть копию файла example.docx, хранящегося в библиотеке документов по адресу http: /// MySite / Documents, введите следующую команду:

/ ч http: //MySite/Documents/example.docx

Примечание. Если документ отмечен, переключатель / h не действует. Word открывает файлы, которые вы можете редактировать.

  1. / pxslt: запустить Word и открыть существующий XML-документ на основе указанного XSLT.

Например: Чтобы запустить и применить XSLT MyTransform, хранящийся на диске C, введите следующую команду:

/pc:MyTransform.xsl c: Data.sml

  1. / a: запустить Word и запретить автоматическую загрузку общих надстроек и шаблонов (включая обычные шаблоны). Ключ / a также блокирует установочные файлы.
  2. / ladd-in: откройте Word, а затем загрузите определенную надстройку Word.

Например: чтобы открыть Word и загрузить надстройку Sales.dll, хранящуюся на диске C, введите следующую информацию:

/ic:Sales.dll

Примечание. Не оставляйте пробелов между переключателем и именем надстройки.

  1. / m: запустить Word без запуска макросов AutoExec.
  2. / mmacroname: открыть Word и запустить определенный макрос. Переключатель m / также запрещает выполнение макроса AutoExec словом.

Например: чтобы запустить Word, а затем запустить макрос Salelead, введите следующее:

/ mSalelead

Примечание. Между переключателем и именем макроса нет пробела.

  1. / n: открыть новую версию Word, не открывая документ. Документы, открытые в каждой версии Word, не будут отображаться в качестве параметров в списке переключателей Windows для других версий.
  2. / w: запустить новую версию Word с пустым документом. Документы, открытые в каждой версии Word, не будут отображаться в качестве параметров в списке переключателей Windows для других версий.
  3. / r: повторно зарегистрировать Word в реестре Windows. Этот переключатель запускает Word, запускает программу установки Office, обновляет реестр Windows.
  4. / x: открыть Word из операционной оболочки, чтобы Word отвечал только на запрос DDE (например, для печати документов программно).
  5. / ztemplatename: отображать точно так же, как переключатель / t. Однако вы можете использовать переключатель / z в Word для создания событий запуска и нового, в то время как переключатель / t создает только события запуска.

Теперь вы должны иметь возможность открывать Word по-разному, следуя приведенным выше командам.

Желаю всем успехов!

Как (и почему) запустить Microsoft Word из командной строки

Как и большинство приложений, вы можете запускать Word из командной строки, но Word также поддерживает несколько дополнительных переключателей для управления процессом запуска.

Независимо от того, вводите ли вы команду в командной строке, используете ее для создания ярлыка, вставляете ее как часть пакетного сценария, запуск Word с дополнительными параметрами позволяет вам делать такие вещи, как запуск Word в безопасном режиме для устранения неполадок или запуск с определенным шаблоном.

Использование командной строки для запуска Word

Прежде чем мы сможем открыть Word с помощью командной строки, нам нужно выяснить, в каком каталоге находится файл winword.exe. Вы можете сделать это вручную или просто попросите командную строку найти это за вас. Для этого откройте командную строку, открыв меню «Пуск», набрав «cmd» и выбрав приложение «Командная строка».

Когда вы откроете командную строку, вы окажетесь в каталоге верхнего уровня — папке вашей учетной записи. Нам нужно копнуть глубже, зайдя в каталог Program Files. Сделайте это, введя следующую команду и нажав Enter:

cd «программные файлы (x86)»

Программные файлы в командной строке

Теперь вы окажетесь в каталоге Program Files. Следующим шагом является поиск каталога, в котором находится файл winword.exe. Для этого введите следующую команду и нажмите «Enter».

каталог winword.exe / s

После ввода этой команды командная строка сама найдет каталог.

Каталог Winword

Теперь, когда вы знаете каталог, в котором находится файл winword.exe, вы можете использовать команду cd, чтобы открыть путь к файлу. В этом примере вам нужно будет ввести следующую команду:

компакт-диск Microsoft OfficerootOffice16

Теперь вы должны оказаться в каталоге, в котором находится winword.exe.

Откройте файл Winword

Теперь, если вы хотите открыть Microsoft Word так же, как если бы вы открывали его с помощью его значка, все, что вам нужно сделать, это ввести winword и затем нажать «Enter», и Word откроется обычным способом.

Открыть нормальное слово

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

Общие параметры и параметры командной строки Word

Заимствовано из официальный сайт поддержки Microsoft Office , вот список некоторых возможных способов открыть Word вместе с соответствующей командой.

Работа с файлами Office 2007 из командной строки

После того как Microsoft ввела новые форматы в пакете Office 2007 жить пользователям стало гораздо интересней. Несовместимость с предыдущими версиями без установки конвертера и попытки привыкнуть к интерфейсу в виде ленты были лишь малой частью возникших проблем. Но данная статья не об этом, она о том, что можно сделать с документом формата Office 2007/2010 из командной строки, даже если у вас не установлен Microsoft Office.

Сначала немного теории, формат Office 2007/2010 представляет собой подвид XML, внутри он содержит специальным образом отформатированный текст с которым можно работать любым текстовым редактором. Снаружи мы видим файл с расширением docx, представляющий собой архив формата ZIP. Следовательно, для работы нам понадобится архиватор понимающий ZIP и блокнот. Все действия мы будем автоматизировать используя bat файлы.

Для начала нам понадобится исходный документ формата docx. Его можно создать самостоятельно или взять из архива, вместе с остальными примерами к статье. Для начала создадим на диске C папку для рабочих файлов и назовем ее OfficeXMLBat. С помощью Microsoft Word создаем внутри папки документ с именем Source.docx примерно такого содержания:

Для начала мы сделаем так, чтобы после запуска пакетного файла в поле Дата автоматически прописывалась сегодняшняя дата. Для начала нам необходимо выбрать архиватор работающий со стандартными ZIP архивами, остановим свой выбор на 7-ZIP. Из всего комплекта поставки , для работы в консоли, нам понадобятся только два файла 7z.exe и 7z.dll. Для тех у кого этот архиватор уже установлен необходимые файлы обычно находятся в папке Program Files7-Zip, остальным проще взять эти файлы из архива или установить 7-ZIP. Сначала извлечем содержимое из документа Source.docx в папку Source, сделать это можно из вашего любимого архиватора или из консоли 7z.exe x Source.docx -oC:OfficeXMLBatSource -aoa. В результате в папке Source будет создан набор файлов из которых и состоит документ формата Office 2007/2010. Из всех представленных файлов нам будет интересен только один, из папки word, с именем document.xml, в котором и хранится содержимое документа. Откроем его в обычном блокноте или вашем любимом HEX редакторе (правой кнопкой по файлу — Открыть с помощью — Блокнот ;). Внутри ищем строку 01.05.1980, которую мы будем менять на сегодняшнюю дату. Принцип работы будет такой — мы выделяем и копируем весь текст до строки 01.05.1980 после чего вставляем его в отдельный файл, а потом копируем содержимое после строки 01.05.1980 и вставляем в другой файл. Для работающих в блокноте понадобится открыть еще один экземпляр блокнота, в который будет вставляться результат копирования. При сохранении из блокнота не забываем выбрать кодировку UTF-8 и поместить результат в папку OfficeXMLBat.

В примере, первый файл называется part1.txt, а второй part2.txt. Описание как надо выделять, копировать и сохранять в блокноте, я опущу — должен же быть у этой статьи минимальный порог вхождения ;). В результате у нас получается две половинки исходного файла с вырезанной датой. Легко представить, что склеив две половинки с сегодняшней датой и вставив получившийся файл обратно в архив мы получим нужный нам результат. Осталось это все реализовать в виде bat файла.
Сначала определимся откуда будет запускаться командный файл, для нас это папка на диске c с именем OfficeXMLBat, поэтому первой строкой в командном файле будет переход в эту папку:

Теперь выведем в файл с именем date.txt сегодняшнюю дату

Склеим файлы part1.txt date.txt part2.txt в один общий файл с именем document.xml и сохраним его в папку Sourceword

Осталось собрать документ обратно, заархивировав содержимое папки Source в документ с именем Create.docx

На этом написание скрипта закончено, после запуска получившегося батника в папке появится файл Create.docx, открыв который мы увидим сегодняшнюю дату

Весь получившийся батник сохранен в файле create.bat, исходный текст:

В принципе этого достаточно для понимания как это все работает. Создадим еще один пример, более сложный. В файл Create2.docx будем добавлять не только дату, но и время, кроме того будем проверять папку на наличие файла report1.txt, если он есть то в колонке «Отчет сдал» впишем Да, иначе Нет. Получится этакая система контроля сдачи отчета.

Для начала разрежем файл document.xml на 4 части, разделителями послужат строки Дата (01.05.1980), Время (10:55), Отчет сдал (Да). В результате в папке будет 4 новых файла, part1b.txt part2b.txt part3b.txt part4b.txt, которые мы будем склеивать в новый документ. Осталось переписать скрипт:

Первые три строчки это переход в нужную папку и вывод текущего времени и даты в соответствующие файлы. Потом идет проверка существования файла report1.txt и, в зависимости от этого, в файл rep.txt выводится Yes или No. Последние две строки склеивают все в один документ и упаковывают его в архив. Дабы не засорять пример непечатными символами в примере Да/Нет выводится на английском языке, в готовом варианте здесь можно писать по русски, но только в кодировке UTF-8, например сохраняя файл из блокнота. После запуска скрипта и открытия файла Create2.docx мы увидим следующее:

Заботливый Word подчеркнул надпись на английском, но в целом поставленная задача успешно решена. Если в нашу рабочую папку закинуть файл report1.txt любого размера, то после запуска скрипта надпись No сменится на Yes, что как бы показывает что отчет сдан.

Подобный метод несложно распространить на Linux/Unix и любые другие системы со встроенным скриптовым языком. В принципе то же самое может делать простейшая программа на любом языку высокого уровня, но помня как, сисадмины относятся к незнакомым exe файлам на сервере, консольный метод можно тоже признать жизнеспособным. Недостатком можно посчитать привязку к архиватору 7-Zip, но использовать архивацию в ZIP, встроенную в Windows, из консоли неудобно, а другие консольный архиваторы никто не отменял. В конце концов, можно воспользоваться DOS архиватором родом из 80-х PKZIP или написать оболочку для zlib — простор для модификаций огромен ;). Все примеры к статье можно скачать здесь.

Запустить Word 2013 из командной строки

У некоторых наших клиентов есть проблема, которую мы не можем воспроизвести здесь: наше программное обеспечение использует MS-Word для создания формных писем. Поскольку некоторые из наших клиентов используют Office 2013, эта функция больше не будет работать.
Мы попытались воспроизвести это и обнаружили, что в уязвимых системах Word не запускается из командной строки. Запуск по ссылке в стартовом меню работает. Он также работает для запуска Excel из командной строки.

Есть ли у кого-нибудь идеи, в чем проблема и как ее решить?

5 ответов

Мы нашли решение: наше программное обеспечение по-прежнему использует старые имена файлов 8.3 — также длинные имена файлов заменяются короткими. И похоже, что Office 2013 их больше не любит.

Попробуйте использовать приглашение запуска, нажав кнопку Windows + R. Откроется окно запуска, а затем введите winword , чтобы открыть MS Word, и excel , чтобы открыть MS Excel.

Это расположение и файл исполняемого файла в Office 2013, как указано в ярлыке. Вы также не можете запустить его с помощью winword в 32-разрядной версии Win 8.

На чтение 5 мин. Просмотров 3.8k. Опубликовано 21.06.2019

Как и большинство приложений, вы можете запускать Word из командной строки, но Word также поддерживает несколько дополнительных параметров для управления процессом запуска.

Вводите ли вы команду в командной строке, используйте ее для создания ярлыка, вставьте ее как часть пакетного сценария, запуск Word с дополнительными параметрами позволяет выполнять такие действия, как запуск Word в безопасном режиме для устранения неполадок или запуск с определенного шаблона.

Использование командной строки для запуска Word

Прежде чем мы сможем открыть Word с помощью командной строки, нам нужно выяснить, в каком каталоге находится файл winword.exe. Вы можете сделать это вручную, или вы можете просто найти командную строку для вас. Для этого откройте командную строку, откройте меню «Пуск», введите «cmd» и выберите приложение «Командная строка».

Когда вы откроете командную строку, вы окажетесь в каталоге верхнего уровня – папке вашей учетной записи пользователя. Нам нужно копать глубже, зайдя в каталог Program Files. Сделайте это, введя следующую команду и нажав Enter:

cd “программные файлы (x86)”

Теперь вы будете в каталоге Program Files. Следующий шаг – найти каталог, в котором находится файл winword.exe. Сделайте это, набрав следующую команду и нажав «Enter».

dir winword.exe/s

Как только вы введете эту команду, командная строка найдет каталог для вас.

Теперь, когда вы знаете каталог, в котором находится файл winword.exe, вы можете использовать команду cd, чтобы открыть путь к файлу. В этом примере вам нужно будет ввести следующую команду:

cd Microsoft Office root Office16

Теперь вы должны быть в каталоге, где находится winword.exe.

Теперь, если вы хотите открыть Microsoft Word так же, как если бы вы открывали его с помощью его значка, все, что вам нужно сделать, это набрать winword и затем нажать «Enter», и Word откроет его обычным способом ,

Однако весь смысл использования команды в том, что вы можете использовать различные параметры и параметры, которые она предлагает.

Общие параметры командной строки Word и параметры

Заимствованный из официального сайта поддержки Microsoft Office, здесь приведен список некоторых возможных способов открытия Word вместе с соответствующей командой.

Переключатель и параметр Описание

/безопасно Запускает Word в безопасном режиме. Это запускает Word без каких-либо дополнительных надстроек, шаблонов и других настроек. Это полезно при устранении проблем в Word.

Вы также можете запустить Word в безопасном режиме, удерживая нажатой клавишу Ctrl при запуске Word из меню «Пуск», и создание ярлыка с этим параметром делает это намного проще.

Запускает Word без отображения заставки Word.

/ttemplatename Запускает Word с новым документом на основе шаблона, отличного от шаблона Normal.

Пример . Предположим, что мы хотим открыть документ, хранящийся на диске C с именем example.docx, мы набрали следующую команду:

/tc:example.docx

Примечание. Не ставьте пробел между параметром и именем файла.

/t filename Запускает Word и открывает существующий файл.

Пример . Чтобы запустить Word и открыть существующий файл example.docx, хранящийся на диске C, введите следующее:

/t c: example.docx

Чтобы открыть несколько файлов example.docx и example2.docx, расположенных одновременно на диске C, введите следующее:

/t c: example.docx c: example2.docx

/f filename Запускает Word с новым документом на основе существующего файла.

Пример . Чтобы запустить Word и создать новый документ на основе файла example.docx, хранящегося на рабочем столе, введите следующее:

/f «c: Documents and Settings Все пользователи Desktop example.docx

/h http: // filename Запускает Word и открывает доступную только для чтения копию документа, который хранится на сайте Microsoft Windows SharePoint Services. Сайт должен быть на компьютере под управлением Word 2007 или более поздней версии или Windows SharePoint Services 2.0 или более поздней версии.

Пример . Чтобы запустить Word и открыть копию файла example.docx, хранящегося в библиотеке документов по адресу http: // MySite/Documents, введите следующее:

/h http: // MySite/Documents/example.DOCX

Примечание. Если документ извлечен для вас, параметр/h не действует. Word открывает файлы, чтобы вы могли их редактировать.

/pxslt Запускает Word и открывает существующий документ XML на основе указанного XSLT.

Пример . Чтобы запустить и применить XSLT MyTransform, сохраненный на диске C, введите следующее:

/pc:MyTransform.xsl c: Data.sml

Запускает Word и предотвращает автоматическую загрузку надстроек и глобальных шаблонов (включая шаблон Normal). Параметр/a также блокирует файлы настроек.

/Лэдд в Запускает Word, а затем загружает определенную надстройку Word.

Пример . Чтобы запустить Word и загрузить надстройку Sales.dll, хранящуюся на диске C, введите следующее:

/ic:Sales.dll

Примечание. Не вводите пробел между коммутатором и именем надстройки.

Запускает Word без запуска макросов AutoExec.

/mmacroname Запускает Word и запускает определенный макрос. Переключатель m/также запрещает запуску макросов AutoExec word.

Пример . Чтобы запустить Word, а затем запустить макрос Salelead, введите следующее:

/mSalelead

Примечание. Не вставляйте пробел между переключателем и именем макроса.

/п Запускает новый экземпляр Word без открытого документа. Документы, открытые в каждом экземпляре Word, не будут отображаться в качестве вариантов выбора в списке Switch Windows других экземпляров.

Запускает новый экземпляр Word с пустым документом. Документы, открытые в каждом экземпляре Word, не будут отображаться в качестве вариантов выбора в списке Switch Windows других экземпляров.

Перерегистрируйте Word в реестре Windows. Этот переключатель запускает Word, запускает программу установки Office, обновляет реестр Windows и закрывает.

Запускает Word из оболочки операционной системы, чтобы Word отвечал только на один запрос DDE (например, программная печать документа).

/ztemplatename Видимо ведет себя так же, как ключ/t. Однако вы можете использовать ключ/z с Word для генерации как запуска, так и нового события, тогда как ключ/t генерирует только событие запуска.

Вот и все, что нужно сделать! Теперь вы сможете открыть Word любым конкретным способом, просто выбрав эти команды.

Как делать скриншоты с Word 2010

Одна из новых функций Word 2010 – возможность

378

Как добавить боковые части и получить цитаты в документы Microsoft Word

Боковые заголовки (где подзаголовки документа отображаются

1.6k.

Как создать буквицу в Word 2013

Буквица – это декоративный элемент, обычно используемый

277

Как использовать функцию «Показать форматирование» в Word 2010

Вы привыкли к функции выявления кодов в WordPerfect?

117

Как напечатать в Word, чтобы оставить место для дырокола

Перфораторы отлично подходят для аккуратной вставки

606

Как использовать сноски в Microsoft Word 2010

Сноска – это примечание, которое появляется внизу

172

Как создавать, редактировать и просматривать документы Microsoft Word бесплатно

Было время, когда вам приходилось устанавливать Microsoft

530

Как отображать непечатные символы в Word

Помимо обычного содержимого ваших документов в Word

85

Как и большинство приложений, вы можете запускать Word из командной строки, но Word также поддерживает несколько дополнительных переключателей для управления процессом запуска.

Независимо от того, вводите ли вы команду в командной строке, используете ее для создания ярлыка, вставляете ее как часть пакетного сценария, запуск Word с дополнительными параметрами позволяет вам делать такие вещи, как запуск Word в безопасном режиме для устранения неполадок или запуск с определенным шаблоном.

Прежде чем мы сможем открыть Word с помощью командной строки, нам нужно выяснить, в каком каталоге находится файл winword.exe. Вы можете сделать это вручную или просто попросите командную строку найти это за вас. Для этого откройте командную строку, открыв меню «Пуск», набрав «cmd» и выбрав приложение «Командная строка».

Когда вы откроете командную строку, вы окажетесь в каталоге верхнего уровня — папке вашей учетной записи. Нам нужно копнуть глубже, зайдя в каталог Program Files. Сделайте это, введя следующую команду и нажав Enter:

cd «программные файлы (x86)»

Программные файлы в командной строке

Теперь вы окажетесь в каталоге Program Files. Следующим шагом является поиск каталога, в котором находится файл winword.exe. Для этого введите следующую команду и нажмите «Enter».

каталог winword.exe / s

После ввода этой команды командная строка сама найдет каталог.

Каталог Winword

Теперь, когда вы знаете каталог, в котором находится файл winword.exe, вы можете использовать команду cd, чтобы открыть путь к файлу. В этом примере вам нужно будет ввести следующую команду:

компакт-диск Microsoft OfficerootOffice16

Теперь вы должны оказаться в каталоге, в котором находится winword.exe.

Откройте файл Winword

Теперь, если вы хотите открыть Microsoft Word так же, как если бы вы открывали его с помощью его значка, все, что вам нужно сделать, это ввести winword и затем нажать «Enter», и Word откроется обычным способом.

Открыть нормальное слово

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

Общие параметры и параметры командной строки Word

Заимствовано из официальный сайт поддержки Microsoft Office, вот список некоторых возможных способов открыть Word вместе с соответствующей командой.

Что вы думаете об этой статье?

Download PC Repair Tool to quickly find & fix Windows errors automatically

Microsoft Word has several useful command-line switches that can be used to start Word. These switches can be used to make Word run in a specific way or perform specific tasks – like if you want to start it in the Safe Mode without any addons.

To open a Word document using the switches in Windows 10/8/7, type winword.exe /x. Here “/x” is the switch.

To modify how Microsoft Office Word starts on a one-time basis, you can add switches to the Microsoft Windows Run command (Start menu).

The following is the list of switches for Microsoft Word:

Switch and parameter Description
/safe Starts Word in Safe Mode.
/q Starts Word without displaying the Word splash screen.
/ttemplatename Starts Word with a new document based on a template other than the Normal template.

Example    To start Word with a document based on a template called Myfax.dotx, stored on the C drive, type the following at the command prompt:

/tc:Myfax.dotx

Note: Do not include a space between the switch and the name of the template file.

Security Note: Because templates can store macro viruses, be careful about opening them or creating files based on new templates. Take the following precautions: run up-to-date antivirus software on your computer, set your macro security level to high, clear the Trust all installed add-ins and templates check box, use digital signatures, and maintain a list of trusted sources.

/t filename Starts Word and opens an existing file.

Example    To start Word and open the template file Myfax.dotx, stored on the C drive, type the following at the command prompt:

/t c:Myfax.dotx

Example    To start Word and open multiple files, such as MyFile.docx and MyFile2.docx, each stored on the C drive, type the following at the command prompt:

/t c:MyFile.docx c:MyFile2.docx

/f filename Starts Word with a new document based on an existing file.

Example    To start Word and create a new document based on file MyFile.docx, stored on the desktop, type the following at the command prompt:

/f “c:Documents and SettingsAll UsersDesktopMyFile.docx”

/h http://filename Starts Word and opens a read-only copy of a document that is stored on a Microsoft Windows SharePoint Services site. The site must be on a computer that is running Word 2007 or later or Windows SharePoint Services 2.0 or later.

Example    To start Word and open a copy of file MyFile.docx, stored in a document library at the URL http://MySite/Documents, type the following at the command prompt:

/h http://MySite/Documents/MyFile.docx

Note: If the document is checked out to you, the /h switch has no effect. Word opens the file so that you can edit it.

/pxslt Starts Word and opens an existing XML document based on the specified Extensible Stylesheet Language Transformation (XSLT).

Example    To start Word and apply the XSLT MyTransform, stored on the C drive, to the XML file Data.xml, also stored on the C drive, type the following at the command prompt:

/pc:MyTransform.xsl c:Data.xml

/a Starts Word and prevents add-ins and global templates (including the Normal template) from being loaded automatically. The /a switch also locks the setting files.
/ladd-in Starts Word and then loads a specific Word add-in.

Example    To start Word and then load the add-in Sales.dll, stored on the C drive, type the following at the command prompt:

/lc:Sales.dll

Note: Do not include a space between the switch and the add-in name.

Security Note: Use caution when running executable files or code in macros or applications. Executable files or code can be used to carry out actions that might compromise the security of your computer and data.

/m Starts Word without running any AutoExec macros.
/mmacroname Starts Word and then runs a specific macro. The /m switch also prevents Word from running any AutoExec macros.

Example    To start Word and then run the macro Salelead, type the following at the command prompt:

/mSalelead

Note: Do not include a space between the switch and the macro name.

Because macros can contain viruses, be careful about running them. Take the following precautions: run up-to-date antivirus software on your computer; set your macro security level to high; clear the Trust all installed add-ins and templates check box; use digital signatures; maintain a list of trusted publishers.

/n Starts a new instance of Word with no document open. Documents opened in each instance of Word will not appear as choices in the Switch Windows list of other instances.
/w Starts a new instance of Word with a blank document. Documents opened in each instance of Word will not appear as choices in the Switch Windows list of the other instances.
/r Re-registers Word in the Windows registry. This switch starts Word, runs Office Setup, updates the Windows registry, and then closes.
/x Starts Word from the operating system shell so that Word responds to only one Dynamic Data Exchange (DDE) request (for example, to print a document programmatically).
/ztemplatename

Visibly behaves exactly like the /t switch. However, you can use the /z switch with Word to generate both a Startup and a New event, whereas the /t switch generates only a Startup event.

If you plan to use a modified startup method frequently, you can create a shortcut on the Windows desktop, using these switches.

You can get the command line switches for Word, Excel, PowerPoint, Outlook and Access here at KB210565.

Ezoic

Anand Khanse is the Admin of TheWindowsClub.com, a 10-year Microsoft MVP (2006-16) & a Windows Insider MVP (2016-2022). Please read the entire post & the comments first, create a System Restore Point before making any changes to your system & be careful about any 3rd-party offers while installing freeware.

Понравилась статья? Поделить с друзьями:

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

  • Как запустить word в безопасном режиме windows 10
  • Как запустить word бесплатно
  • Как запустить word 2016
  • Как запустить word 2007 от имени администратора
  • Как запустить sql в excel

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

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