function close_excel_if_open(filename)
%CLOSE_EXCEL_IF_OPEN  Close an Excel workbook if it is currently open.
%
%   close_excel_if_open(filename)
%
%   filename may be a relative or absolute path.  If Excel is not running,
%   or if the workbook is not open, the function exits silently.
%
%   Windows only (uses COM / ActiveX).

    if nargin < 1 || isempty(filename)
        return
    end

    % Ensure filename is char (App Designer may pass string)
    filename = char(filename);

    % Convert to absolute path if needed
    if ~contains(filename, filesep)
        filename = fullfile(pwd, filename);
    end

    % If file does not exist on disk, nothing to close
    if exist(filename, 'file') ~= 2
        return
    end

    % Try to connect to a running Excel instance
    try
        excel = actxGetRunningServer('Excel.Application');
    catch
        return   % Excel not running
    end

    % Target workbook name only (Excel Workbooks are keyed by Name, not path)
    [~, name, ext] = fileparts(filename);
    targetName = [name ext];

    % Loop through open workbooks
    try
        nWB = excel.Workbooks.Count;
    catch
        return
    end

    for k = nWB:-1:1
        try
            wb = excel.Workbooks.Item(k);
            if strcmpi(wb.Name, targetName)
                wb.Close(false);   % false = do not save
            end
        catch
            % Ignore any workbook-level errors
        end
    end
end
