Select worksheet in Excel using OLE Automation

Problem: you want to select a worksheet to which you will export data using ABAP OLE Automation.

Solution: All you need to do is use below code and it will work like a charm.

  TYPE-POOLS:
    ole2.
 
  DATA:
    lv_excel TYPE ole2_object,
    lv_workbook TYPE ole2_object,
    lv_sheet TYPE ole2_object. 
 
* start Excel
  CREATE OBJECT lv_excel 'EXCEL.APPLICATION'.
  CHECK sy-subrc = 0.
 
* make it visible
  SET PROPERTY OF lv_excel 'VISIBLE' = 1.
 
* open the file
  CALL METHOD OF lv_excel 'WORKBOOKS' = lv_workbook.
  CALL METHOD OF lv_workbook 'OPEN' EXPORTING #1 = 'c:\myExcelFile.xls'.
 
* Open the first sheet in the workbook
  CALL METHOD OF lv_excel 'WORKSHEETS' = lv_sheet EXPORTING #1 = 1.
  CALL METHOD OF lv_sheet 'ACTIVATE'.
 
  FREE OBJECT:
    lv_sheet,
    lv_workbook,
    lv_excel.
  TYPE-POOLS:
    ole2.

  DATA:
    lv_excel TYPE ole2_object,
    lv_workbook TYPE ole2_object,
    lv_sheet TYPE ole2_object. 

* start Excel
  CREATE OBJECT lv_excel 'EXCEL.APPLICATION'.
  CHECK sy-subrc = 0.

* make it visible
  SET PROPERTY OF lv_excel 'VISIBLE' = 1.

* open the file
  CALL METHOD OF lv_excel 'WORKBOOKS' = lv_workbook.
  CALL METHOD OF lv_workbook 'OPEN' EXPORTING #1 = 'c:\myExcelFile.xls'.

* Open the first sheet in the workbook
  CALL METHOD OF lv_excel 'WORKSHEETS' = lv_sheet EXPORTING #1 = 1.
  CALL METHOD OF lv_sheet 'ACTIVATE'.

  FREE OBJECT:
    lv_sheet,
    lv_workbook,
    lv_excel.

Komentowanie jest zakończone.