Command line in excel

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.

Вы можете

Откройте Microsoft Excel

из командной строки, и вы также можете добавить дополнительные параметры в команду, чтобы сделать такие вещи, как открытый Excel с определенным шаблоном, или

Запустите Excel в безопасном режиме

для устранения неполадок.

Запустите Excel с помощью командной строки

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

Во-первых, есть простой способ.

Откройте командную строку

Набирая «CMD» в панели поиска Windows и нажав приложение командной строки из результатов поиска.

Команда подсказки откроется. Чтобы запустить Excel, введите эту команду и нажмите Enter:

 Начните Excel 

Excel должен запустить немедленно.

Другим способом открытия Excel является установлением каталога, который содержит файл Excel.exe, изменяясь к этому каталогу в командной строке, а затем запустить простую команду.

Чтобы найти файл Excel.exe, вам нужно будет в каталоге файлов программы в командной строке. Вы можете

использовать

CD

команда

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

 CD  "Файлы программы" 

Теперь вы будете сейчас в каталоге файлов программы. Далее необходимо выяснить, в каком каталоге находится файл excel.exe. Для этого запустите эту команду:

 Dir Excel.exe / S 

Каталог файла Excel.exe будет возвращен.

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

 CD Microsoft Office  root  office16 

Теперь, когда вы в правильном каталоге, все, что осталось сделать, это напечатать

преступность

в командной строке и нажмите Enter.

Excel теперь откроется. Тем не менее, основной целью запуска Excel из командной строки, так что вы можете контролировать

как

Он открывается, и вы делаете это, добавляя различные коммутаторы и параметры, которые доступны для команды.

Выключатели и параметры командной строки Excel

Вот список коммутаторов команд, предоставленных

Официальный сайт поддержки Microsoft Office

Отказ Добавьте их в конец

Начать Excel

Команда в командной строке.


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

Описание


Путь рабочего тетра

|.

имя файла

Переключатель не требуется.

Открывает целевой файл.


Пример:



Запустите Excel «C: Пример папки file_name1.xlsx»

или



Начать Excel http: //mysite/file_name1.xlsx





Путь рабочего тетра

|.

имя файла

Открывает целевую рабочую книгу как только для чтения.


Пример:



Начать Excel / R «C: Пример папки file_name1.xlsx»

или



Запустите Excel / R http: //mysite/file_name1.xlsx


/ Т.

|.

Вы также можете использовать

/ N.

вместо того

/ Т.

достичь того же результата.

Открывает целевой файл как шаблон.


Пример:



Запустите Excel / T «C: Пример папки file_name1.xlsx»

или



Запустите Excel / T http: //mysite/file_name1.xlsx


/ E.

или

/ встраивать
Предотвращает появление экрана запуска Excel и новой пустой рабочей книги от открытия.

/ S.

или

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

/ М.
Создает новую рабочую книгу, которая содержит один макро-лист XLM.

/ а
Загружает надстройку автоматизации, указанное Progid Add-In.


Пример:



Начать Excel / myprogid.myprogid2.1


/Икс
Начинается отдельный процесс Excel.

Используя эти команды, вы можете открыть Excel несколькими различными способами.

Excel — это не единственная программа Office, которую вы можете открыть с командной строкой, вы также можете использовать его для запуска

Microsoft Word

а также

Силовая установка

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

You can use command-line parameters to launch Microsoft Excel from the Run dialog box or by configuring the command and switches in a desktop shortcut. Launch Excel with command-line switches from the Run dialog box if you only want to use the switches once. Create a desktop shortcut to implement a solution for launching Excel each time with command-line parameters. You can open a workbook as read-only, launch additional instances of Excel, and invoke several other options using command-line switches.

Run Box

  1. Press “Windows-R” to open the Run box in Windows 8.

  2. Type “excel.exe” into the Run input box. You can also click the “Browse” button, and then navigate to and click on the Excel EXE file to load the command into the Run box.

  3. Type a space, and then type “/” followed by the first switch. For example, type “excel.exe /e” to launch Excel without opening a blank workbook or displaying the Start screen.

  4. Type a space, and then type “/” followed by the second switch. Continue adding switches until all command-line parameters are defined.

  5. Click “OK” or press the “Enter” key to execute the command.

Desktop Shortcut

  1. Click the “Desktop” tile to open the Windows 8 desktop.

  2. Right-click on an empty space on the desktop, and then click “New” from the context menu.

  3. Click “Shortcut” to open the Shortcut dialog box.

  4. Type a quotation mark, and then type the full path to the Excel EXE file in the Shortcut input box. Microsoft Excel 2013 installs to C:Program FilesMicrosoft OfficeOffice15excel.exe by default. You can also click “Browse,” and then browse to the Excel EXE file to insert the path in the input box. Enclose the path with a second quotation mark.

  5. Type a space, and then type “/” (without quotes) followed by the first switch.

  6. Type a space, and then type “/” (without quotes) followed by the second switch. Continue adding switches until all command-line parameters are defined. Click “Next.”

  7. Type a name for the shortcut in the Type a Name for This Shortcut box, and then click “Finish.” The shortcut is created with command-line parameters.

  8. Click the new shortcut to launch Excel with the command-line switches.

To Run an Excel VBA macro from the command line has the advantage of convenience. With a few simple keystrokes, we can execute tasks that would otherwise require many keystrokes in the Graphical User Interface (GUI).

Because it is not possible to execute an Excel macro outside of Excel, the only way we can run a macro from the command line is to use a VBScript. VBScript is an executable text file with a .vbs file extension.

The VBScript is natively supported by Windows operating system and therefore can be executed outside of the Excel Application and other MS Office applications.

The VBScript we will create in this tutorial launches the Excel Application, opens the Excel file in hidden mode, and runs the VBA macro.

In this tutorial, we will first create a macro that imports data into Excel from a Word Table. Then we will create a VBScript that we can launch from the command line and have the macro executed.

Create a macro that imports data from the Word table

We will use the following Word table to show how we can import data from a Word table into an Excel file. The table shows details of different products:

Supplier ID Item Type Product ID Product Name Product Code Bin Picking Number
1 Product 4563 ACB PSU 660 AC-ll00007 AC
2 Product 4569 ITR KBD M6 AC-ll00008 AC
3 Product 5489 MSF HDS LIF AC-ll00009 AC
4 Product 6485 MSF MSE MOBILE AC-ll00010 AC
5 Product 7245 MSF KBD AC-ll00011 AC

A macro that can import data from word tables into Excel is very useful because many people are comfortable with Word and find it easier to work with Word than Excel. But Word does not have the powerful data analysis tools that Excel has.

When the macro imports the data we can apply Excel’s powerful data analysis tools to analyze it.

We create the macro by using the following steps:

  1. Press Alt + F11 to open the Visual Basic Editor (VBE).
  2. Insert a module and type in the code below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

Sub importWordTableData()

    Dim wdApp       As Object

    Dim wdDoc       As Object

    Dim xlSheet     As Worksheet

    Dim wdTable     As Object

    Dim wdCell      As Object

    Dim i           As Long, j As Long

    On Error Resume Next

    Set wdApp = GetObject(, «Word.Application»)

    If Err Then

        Set wdApp = CreateObject(«Word.Application»)

    End If

    On Error GoTo 0

    Set xlSheet = ActiveSheet

    Set wdDoc = wdApp.Documents.Open(«C:filesProduct List.docx») ‘Use the full path of the document with the table

    Set wdTable = wdDoc.Tables(1) ‘This is the first table in the document. For a different table, change the number as appropriate

    For i = 1 To wdTable.Rows.Count

        For j = 1 To wdTable.Columns.Count

            Set wdCell = wdTable.Cell(i, j).Range

            wdCell.End = wdCell.End 1

            xlSheet.Cells(i, j) = wdCell ‘adds the content to the corresponding cell in Excel

        Next j

    Next i

    ‘ Close the Word Document without saving the changes

    wdDoc.Close SaveChanges:=False

    ‘ Quit the application

    wdApp.Quit

    ‘ release system memory assigned to the two variables

    Set wdDoc = Nothing

    Set wdApp = Nothing

End Sub

  1. Place a cursor inside the procedure and press F5 to run it. The macro should run perfectly without any runtime errors if we have to run it successfully from the command line.

The macro opens the Word document and imports the data in the table into the active worksheet of the Excel file:

The macro is working as it should. Select the imported data and delete it so that the macro run by VBScript later can import the data into a blank worksheet.

Let’s see how we can run the macro from the command line.

Create a VBScript file

We first need to create a VBScript file that we can launch from the command line. VBScript is a scripting language developed by Microsoft and is a lighter version of Visual Basic.

VBScript is quite identical to VBA and that is why most VBA scripts can be exported to simple VBScript files.

To create the VBScript we use the following steps:

  1. Open Notepad and type in the following code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

‘Create Excel App Instance & Open Xlsm File

Set objExcelApp = CreateObject(«Excel.Application»)

objExcelApp.Visible = True

objExcelApp.DisplayAlerts = False

‘Define Macro File & Path. You can change it to reflect the path of your Excel file.

sFilePathXlsm = «C:filesRun_VBA_from_Command_Line.xlsm»

Set iWb = objExcelApp.Workbooks.Open(sFilePathXlsm)

‘Run Macro

sMacroToRun = «‘» & sFilePathXlsm & «‘!importWordTableData»

objExcelApp.Run sMacroToRun

‘Save & Close file

iWb.Save

iWb.Close

objExcelApp.DisplayAlerts = True

objExcelApp.Quit

The comments in the code as preceded by an apostrophe and are ignored during program execution.

The comments explain what the code is doing.

  1. Save the file as myMacro.vbs. The file must have a .vbs extension.

For this tutorial, the VBScript is saved in the directory C:UsersSiraliDesktopRun_VBA_from_Command_Line

Run the VBscript from the command line

  1. To open the Command Prompt console type “command prompt” in the Windows start search box and press Enter key. Alternatively, type in “cmd” and press Enter:

  1. At the prompt type the command cd (change directory) followed by a space and then type the path of the VBScript: C:UsersSiraliDesktopRun_VBA_from_Command_Line and press Enter key:

  1. Type in the name of the VBScript myMacro.vbs as follows and then press the Enter key:

The VBScript myMacro.vbs will take some time to run. We can observe as the Word and Excel files are opened and quickly closed.

The VBScript will create an instance of the Excel application. Any alerts are not displayed for there is no need for user intervention. The ideal macros for running from a command line are those that do not require input from users.

Data from the Word table will be imported into Excel.

The Excel file will then be saved and closed

We can open the Excel file and see that the data has been imported:

Conclusion

An Excel VBA macro cannot be run outside of Excel.

In this tutorial, we have seen that the only way a macro can be run from the command line is through a VBScript. VBScript is a scripting language that is a lighter version of Visual Basic.

VBScript is supported natively by Windows and therefore can be executed outside of Excel and other Office applications.

We created a VBScript that opens an instance of Excel and runs the VBA macro. When the macro is finished running the VBScript takes over and saves and closes the Excel Application.

Post Views: 2,757

I have found several snippet of code out there that allows me to pass arguments into excel from command line.

The code below is placed in a new module called parameters:

Declare Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As Long
Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As Long)

Public CmdLineToStr() As String
'
' Returns the command line in the call to Excel
'
Dim Buffer() As Byte
Dim StrLen As Long
Dim CmdPtr As Long

CmdPtr = GetCommandLineW()
If CmdPtr > 0 Then
  StrLen = lstrlenW(CmdPtr) * 2
  If StrLen > 0 Then
    ReDim Buffer(0 To (StrLen - 1)) As Byte
    CopyMemory Buffer(0), ByVal CmdPtr, StrLen
    CmdLineToStr = Buffer
  End If
End If

End Sub

and then in thisworkbook i call this code

Sub workBook_open()
    MsgBox Parameters.CmdLineToStr
End Sub

It fails with the GetCommandLine function, so is the error due to problems with linking the dll library or is this due to the fact that i have some macros stored in personal.xlsb?

I call the excel sheet from the command line with this line:

C:UserskimDesktop>start excel Parameters.xlsm /e/nmbnmbmnb

and i get this error :

eroor

Outside procedure

Понравилась статья? Поделить с друзьями:
  • Command for microsoft excel
  • Command for bold in word
  • Command buttons on excel
  • Command button in word
  • Comma use after the word but