Is there a way to set up start viewing position in excel sheet?

Question:

Normally Excel remembers where you stopped at a sheet and when you open it next time it takes you right there. Is there a way to set up such a position when generating the document?

Asked By: electroiv

||

Answers:

Say we want Sheet2 to be the active sheet and cell Z100 to be at the upper left-hand corner of the window. Place this event macro in the workbook code area:

Private Sub Workbook_Open()
    Sheets("Sheet2").Activate
    Range("Z100").Select
    Application.Goto Reference:=ActiveCell.Address(ReferenceStyle:=xlR1C1), Scroll:=True
End Sub

Because it is workbook code, it is very easy to install and use:

  1. right-click the tiny Excel icon just to the left of File on the Menu Bar
  2. select View Code – this brings up a VBE window
  3. paste the stuff in and close the VBE window

If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx

To remove the macro:

  1. bring up the VBE windows as above
  2. clear the code out
  3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (workbook code), see:

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!

Answered By: Gary's Student

With the pywin32 package, you can control Excel with COM and automate anything that Excel can do.

Here’s an example that creates a simple worksheet, initializes some cells, selects a cell, then saves the document. When you later open the document it will restore to that same location.

import win32com.client

def create_excel_file():
    xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
    # xl.Visible = True # Uncomment to make the Excel COM instance visible
    wb = xl.Workbooks.Add()
    ws = xl.ActiveSheet
    ws.Range('A1').Value = 100
    ws.Range('A2').Value = 200
    ws.Range('B1').Value = 300
    ws.Range('B2').Value = 400
    ws.Range('B2').Select()
    ws.SaveAs(r'test.xlsx')
    xl.Quit()

create_excel_file()

Here’s the resulting file opened in Excel:

test.xlsx content

Answered By: Mark Tolonen