program ExcelTest

  use Excel2016
  use ifcom

  character (len = 100), parameter :: WORKBOOK_PATH = "E:\temp6\ExcelTempTest.xlsx"
  double precision :: val
  integer :: status

  integer(INT_PTR_KIND()) :: excelapp
  integer(INT_PTR_KIND()) :: workbooks
  integer(INT_PTR_KIND()) :: workbook
  integer(INT_PTR_KIND()) :: worksheets
  integer(INT_PTR_KIND()) :: worksheet
  integer(INT_PTR_KIND()) :: range

  type (VARIANT) :: variant1
  type (VARIANT) :: variant2

  ! Initialize.
  excelapp = 0
  workbooks = 0
  workbook = 0
  worksheets = 0
  worksheet = 0
  range = 0
  call VariantInit(variant1)
  call VariantInit(variant2)

  ! Create an Excel object and get the workbooks object.
  call ComInitialize(status)
  call ComCreateObject("Excel.Application", excelapp, status)
  workbooks = $Application_GetWorkbooks(excelapp, $STATUS = status)
  ! Open the workbook, get the worksheets object and the current worksheet.
  workbook = Workbooks_Open(workbooks, trim(WORKBOOK_PATH), $STATUS = status)
  worksheets = $Workbook_GetWorksheets(workbook, status)
  worksheet = $Workbook_GetActiveSheet(workbook, status)

  ! Retrieve values.
  variant1%VT = VT_BSTR
  variant1%VU%PTR_VAL = ConvertStringToBSTR(trim("B6"))
  range = $Worksheet_GetRange(worksheet, variant1, $STATUS = status)
  status = AutoGetProperty(range, "VALUE", val)
  write(6, '(A, F10.2)') "val: ", val
  val = WorksheetFunction_Sum(worksheet, variant1, $STATUS = status)
  write(6, '(A, F10.2)') "sum: ", val

  ! Close the workbook.
  call $Workbook_Close(workbook, $STATUS = status)
  call Workbooks_Close(workbooks, status)
  status = VariantClear(variant1)
  status = VariantClear(variant2)
  if (range /= 0) status = ComReleaseObject(range)
  if (worksheet /= 0) status = ComReleaseObject(worksheet)
  if (worksheets /= 0) status = ComReleaseObject(worksheets)
  if (workbook /= 0) status = ComReleaseObject(workbook)
  if (workbooks /= 0) status = ComReleaseObject(workbooks)
  if (excelapp /= 0) status = ComReleaseObject(excelapp)
  call ComUninitialize()
  
end program ExcelTest
