What the win cmd to open a particular spreadsheet in Excel?

14,079
  1. Paste the following code into a text editor (NotePad, WordPad, Word etc)
  2. Save the file with a "vbs" extension, for example
    ExcelSheet2.vbs
  3. Change this line strFileName = "c:\temp\testa.xlsx" to your desired Excel file path
  4. You can then run this from the commandline by entering the path name of your vbs file

The code has error handling in case the filepath is wrong, or a second sheet isn't present.

[Updated: added further error handling to test for the second sheet being hidden]

sample

Const xlVisible = -1
Dim objExcel
Dim objWb
Dim objws
Dim strFileName
strFileName = "c:\temp\test.xlsx"
On Error Resume Next
Set objExcel = CreateObject("excel.application")
Set objWb = objExcel.Workbooks.Open(strFileName)
Set objws = objWb.Sheets(2)
On Error GoTo 0
If Not IsEmpty(objws) Then
    If objws.Visible = xlVisible Then
        objExcel.Goto objws.Range("a1")
    Else
        wscript.echo "the 2nd sheet is present but is hidden"
    End If
    objExcel.Visible = True
Else
    objExcel.Quit
    Set objExcel = Nothing
    If IsEmpty(objWb) Then
        wscript.echo strFileName & " not found"
    Else
        wscript.echo "sheet2 not found"
    End If
End If
Share:
14,079
inquisitive_one
Author by

inquisitive_one

Updated on June 30, 2022

Comments

  • inquisitive_one
    inquisitive_one almost 2 years

    I know that you can open an Excel file from the win cmd line. But how would you open a particular spreadsheet in that file using win cmd?

  • inquisitive_one
    inquisitive_one about 12 years
    Sorry for the delay. Thanks @brettdj, this worked perfectly for me.