Recent

Author Topic: How to detect if workbook is already opened?  (Read 2614 times)

krzynio

  • Jr. Member
  • **
  • Posts: 99
    • Krzynio's home page
How to detect if workbook is already opened?
« on: October 24, 2017, 06:47:22 pm »
My application opens existing workbook or creates a new one if it doesn't exist.
Next it makes some changes in it, writes them to file and closes the workbook.
When workbook is already opened in Excel or OO then I can also open it and make some changes from my Lazarus app. but when I try to write changes I receive an error.
The goal is to detect if workbook is already opened and close it before opening it by my application.
Can you help how to detect it and close, please.
Ubuntu 23.10 x64, / Windows 11 PL - latest updates
Lazarus 2.2.6, FPC 3.2.2

wp

  • Hero Member
  • *****
  • Posts: 11858
Re: How to detect if workbook is already opened?
« Reply #1 on: October 24, 2017, 07:58:33 pm »
Please try this one, it works for Excel (however, probably not for Calc):
Code: Pascal  [Select][+][-]
  1. uses
  2.   ComObj;
  3.  
  4. // 'd:\workbook.xls' is loaded into Excel.
  5. procedure TForm1.Button2Click(Sender: TObject);
  6. var
  7.   xlApp: OleVariant;
  8. begin
  9.   try
  10.     sWorksheetGrid1.Workbook.WriteToFile('d:\workbook.xlsx', sfOOXML);
  11.   except
  12.     on E:EFCreateError do begin
  13.       if MessageDlg('File is blocked by Excel. Close running Excel instance?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
  14.       begin
  15.         xlapp := GetActiveOleObject('Excel.Application');
  16.         xlapp.Quit;
  17.         ShowMessage('Please save again.');
  18.       end;
  19.     end;
  20.   end;
  21. end;

krzynio

  • Jr. Member
  • **
  • Posts: 99
    • Krzynio's home page
Re: How to detect if workbook is already opened?
« Reply #2 on: October 27, 2017, 07:49:30 am »
Thank you so much.
This is the key:

Code: Pascal  [Select][+][-]
  1. on E:EFCreateError do begin
Ubuntu 23.10 x64, / Windows 11 PL - latest updates
Lazarus 2.2.6, FPC 3.2.2

 

TinyPortal © 2005-2018