none
Excel crashes while creating workbooks using OLE Automation when "Let Windows manage my default printer" is "On" RRS feed

  • Question

  • I have a C++ application that creates Excel workbooks using OLE Automation using #import typelibs and smart pointers implementation.  The application has worked well with various Windows and Office versions for many years.  However, on Windows 10 version 1607 and Office 2016 with "Let Windows manage my default printer" set to "On", Excel is seen to crash during workbook creation.  With any default printer set (including Microsoft XPS Document Writer) no problem is observed.  Crashes during Workbook SaveAs method calls are most common.  The COM error thrown is "The server threw an exception".  Having charts, worksheet headers/footers and cell comment in the workbook seem to be contributing factors but I have not been able to narrow it down to a very specific cause.  Has anyone else experienced the same, and either identified a specific cause or found a work-around (other than using a different default printer)?


    Graham


    • Edited by Graham F Monday, November 14, 2016 12:50 PM Updated conditions for problem based on additional analysis
    Wednesday, October 26, 2016 4:30 PM

All replies

  • Hi Graham F,

    you had mentioned that you got error during Workbook saveAs method called and when the printer is Microsoft print to pdf.

    when you use Microsoft print to PDF at that time it will crate a PDF file in your machine instead of physically printing the file.

    so it is possible that it failed to create PDF and because of that you are getting the error.

    I also find that when someone try to open the word or excel file using HTTP protocol in Internet explorer then this error occurs. are you trying to use HTTP protocol somewhere in your code?

    I suggest you to create a simple program that can reproduce the issue. like just take one file and try to convert it using Microsoft print to PDF.

    you can post your code here and we can try to test that code on our side and try to give you suggestion regarding that.

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, October 27, 2016 8:29 AM
    Moderator
  • Hi, Deepak,

    Thanks for your reply.  I want to clarify that the application is not saving/printing the workbook as a PDF file.  The application is saving the workbook as an Excel workbook (.xls or .xlsb) using the SaveAs method.

    However, my initial analysis was incorrect.  What I have since found is: Excel crashes while creating workbooks using OLE Automation when "Let Windows manage my default printer" is "On".  When a default printer is set (or equivalently when "Let Windows manage my default printer" is "Off") Excel no longer crashes.  The four available printers and scanners listed in Windows Settings | Devices are Fax, Microsoft Print to PDF, Microsoft XPS Document Writer and Send to OneNote 16.  It is known that Excel normally attempts to interact with the printer when text is formatted, etc., so the relationship between Excel and the default printer seems relevant.

    The problem is not observed with Windows 10 Version 1511, i.e. it appears to be new to Windows 10 Version 1067.

    The application does not use HTTP.

    I will try to create a simple program that can reproduce the issue as you have suggested.


    Graham

    Friday, October 28, 2016 6:59 PM
  • Hi Graham F,

    did you resolve your issue?

    if not then you can provide a demo code for us to test.

    if your issue is solved then you can try to update the status of this thread and share the solution with us so that in future if any other community face the same issue then they can refer this thread to get solution.

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, October 31, 2016 2:31 AM
    Moderator
  • The cpp source file below is from a C++ console app (somewhat based on https://code.msdn.microsoft.com/office/CppAutomateExcel-be36992e) with MFC support that demonstrates the problem.  It creates a workbook in the folder from which the console app is executed.  On Windows 10 Version 1607 with Windows managing the default printer and Office 2016, Excel crashes immediately after the console app reports successful completion.  The Excel crash is logged in the Application event log:

    Faulting application name: EXCEL.EXE, version: 16.0.4266.1001, time stamp: 0x55ba1551
    Faulting module name: EXCEL.EXE, version: 16.0.4266.1001, time stamp: 0x55ba1551
    Exception code: 0xc0000005
    Fault offset: 0x000000000017fac8
    Faulting process id: 0xebc
    Faulting application start time: 0x01d2360c55f810b8
    Faulting application path: C:\Program Files\Microsoft Office\Office16\EXCEL.EXE
    Faulting module path: C:\Program Files\Microsoft Office\Office16\EXCEL.EXE
    Report Id: 9674ed27-a1ff-11e6-8107-d067e5371761
    Faulting package full name:
    Faulting package-relative application ID:

    When a default printer is set, Excel no longer crashes.  When ScreenUpdating is not set to false is the console app, Excel no longer crashes.

    // ExcelOLE.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include "ExcelOLE.h"
    
    #ifdef _DEBUG
    #define new DEBUG_NEW
    #endif
    
    #pragma region Import the type libraries
    
    #import "libid:2DF8D04C-5BFA-101B-BDE5-00AA0044DE52" \
        rename("RGB", "MSORGB") \
        rename("DocumentProperties", "MSODocumentProperties")
    // [-or-]
    //#import "C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE12\\MSO.DLL" \
    //    rename("RGB", "MSORGB") \
    //    rename("DocumentProperties", "MSODocumentProperties")
    
    using namespace Office;
    
    #import "libid:0002E157-0000-0000-C000-000000000046"
    // [-or-]
    //#import "C:\\Program Files\\Common Files\\Microsoft Shared\\VBA\\VBA6\\VBE6EXT.OLB"
    
    using namespace VBIDE;
    
    #import "libid:00020813-0000-0000-C000-000000000046" \
        rename("DialogBox", "ExcelDialogBox") \
        rename("RGB", "ExcelRGB") \
        rename("CopyFile", "ExcelCopyFile") \
        rename("ReplaceText", "ExcelReplaceText") \
        no_auto_exclude \
        no_dual_interfaces
    // [-or-]
    //#import "C:\\Program Files\\Microsoft Office\\Office12\\EXCEL.EXE" \
    //    rename("DialogBox", "ExcelDialogBox") \
    //    rename("RGB", "ExcelRGB") \
    //    rename("CopyFile", "ExcelCopyFile") \
    //    rename("ReplaceText", "ExcelReplaceText") \
    //    no_auto_exclude
    
    #pragma endregion
    
    // The one and only application object
    
    CWinApp theApp;
    
    using namespace std;
    
    //
    //   FUNCTION: GetModuleDirectory(LPWSTR, DWORD);
    //
    //   PURPOSE: This is a helper function in this sample. It retrieves the 
    //      fully-qualified path for the directory that contains the executable 
    //      file of the current process. For example, "D:\Samples\".
    //
    //   PARAMETERS:
    //      * pszDir - A pointer to a buffer that receives the fully-qualified 
    //      path for the directory taht contains the executable file of the 
    //      current process. If the length of the path is less than the size that 
    //      the nSize parameter specifies, the function succeeds and the path is 
    //      returned as a null-terminated string.
    //      * nSize - The size of the lpFilename buffer, in characters.
    //
    //   RETURN VALUE: If the function succeeds, the return value is the length 
    //      of the string that is copied to the buffer, in characters, not 
    //      including the terminating null character. If the buffer is too small 
    //      to hold the directory name, the function returns 0 and sets the last 
    //      error to ERROR_INSUFFICIENT_BUFFER. If the function fails, the return 
    //      value is 0 (zero). To get extended error information, call 
    //      GetLastError.
    //
    DWORD GetModuleDirectory(LPWSTR pszDir, DWORD nSize)
    {
        // Retrieve the path of the executable file of the current process.
        nSize = GetModuleFileName(NULL, pszDir, nSize);
        if (!nSize || GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
            *pszDir = L'\0'; // Ensure it's NULL terminated
            return 0;
        }
    
        // Run through looking for the last slash in the file path.
        // When we find it, NULL it to truncate the following filename part.
    
        for (int i = nSize - 1; i >= 0; i--)
        {
            if (pszDir[i] == L'\\' || pszDir[i] == L'/')
            {
                pszDir[i + 1] = L'\0';
                nSize = i + 1;
                break;
            }
        }
        return nSize;
    }
    
    static int PopulateWorksheet(Excel::_ApplicationPtr &spXlApp, Excel::_WorksheetPtr &spXlSheet, LPCTSTR pszName)
    {
        spXlSheet->Name = _bstr_t(pszName);
        _putws(L"The active worksheet is renamed as Report");
    
        _putws(L"Freeze panes");
        Excel::WindowPtr pWindow = spXlApp->ActiveWindow;
        pWindow->SplitColumn = (long) 1;
        pWindow->SplitRow = (long) 1;
        pWindow->FreezePanes = VARIANT_TRUE;
    
        // Fill data into the worksheet's cells.
        _putws(L"Filling data into the worksheet ...");
        spXlSheet->Range[L"A1"]->Value2 = (LPCTSTR) L"One";;
        spXlSheet->Range[L"B1"]->Value2 = (LPCTSTR) L"X-values";
        spXlSheet->Range[L"C1"]->Value2 = (LPCTSTR) L"Y-values";
        spXlSheet->Range[L"D1"]->Value2 = (LPCTSTR) L"Four";
        spXlSheet->Range[L"E1"]->Value2 = (LPCTSTR) L"Five";
        spXlSheet->Range[L"G1"]->Value2 = (LPCTSTR) L"Seven";
        spXlSheet->Range[L"A1:G1"]->Font->Bold = VARIANT_TRUE;
    
        COleVariant var1(COleDateTime((time_t) 100000));
        COleVariant var2(COleDateTime((time_t) 100001));
        COleVariant var3(COleDateTime((time_t) 100002));
        COleVariant var4(COleDateTime((time_t) 100003));
        COleVariant var5(COleDateTime((time_t) 100004));
        spXlSheet->Range[L"B2"]->Value2 = var1;
        spXlSheet->Range[L"B3"]->Value2 = var2;
        spXlSheet->Range[L"B4"]->Value2 = var3;
        spXlSheet->Range[L"B5"]->Value2 = var4;
        spXlSheet->Range[L"B6"]->Value2 = var5;
    
        spXlSheet->Range[L"B:B"]->EntireColumn->NumberFormat = L"[$-F400]h:mm:ss AM/PM";
    
        spXlSheet->Range[L"C2"]->Value2 = (double) 1.1;
        spXlSheet->Range[L"C3"]->Value2 = (double) 2.1;
        spXlSheet->Range[L"C4"]->Value2 = (double) 3.1;
        spXlSheet->Range[L"C5"]->Value2 = (double) 4.4;
        spXlSheet->Range[L"C6"]->Value2 = (double) 5.1;
    
        spXlSheet->Range[L"A:G"]->EntireColumn->AutoFit();
    
        _putws(L"Add bold comment to C1");
        Excel::CommentPtr pComment = spXlSheet->Range[L"C1"]->AddComment(L"This is the comment for cell C1");
        pComment->Shape->TextFrame->AutoSize = VARIANT_TRUE;
        Excel::CharactersPtr pCharacters = pComment->Shape->TextFrame->Characters();
        pCharacters->Font->Bold = VARIANT_TRUE;
    
        _putws(L"Set font for all cells");
        spXlSheet->Cells->Font->Size = (short) 8;
    
        _putws(L"Page setup");
        Excel::PageSetupPtr pPageSetup = spXlSheet->PageSetup;
        pPageSetup->PrintGridlines = VARIANT_TRUE;
        pPageSetup->Orientation = Excel::xlLandscape;
        // Header.
        CString strFmt;
        strFmt.Format(_T("&BBold label:&B %s\r&BBold label 2:&B %s"),
            L"This is the $ thing name",
            L"This is the other $ thing name");
        pPageSetup->LeftHeader = (LPCTSTR) strFmt;
        // Footer.
        pPageSetup->LeftFooter = _T("&BFile:&B &F\rPage &P of &N");
        pPageSetup->RightFooter = (LPCTSTR) L"Version 1.23.456";
    
        return 0;
    }
    
    static int CreateExcelWorkbook()
    {
        // Initializes the COM library on the current thread and identifies the
        // concurrency model as single-thread apartment (STA). 
        // [-or-] CoInitialize(NULL);
        // [-or-] CoCreateInstance(NULL);
        CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    
        try {
            // Create the Excel.Application COM object using the #import 
            // directive and smart pointers.
            Excel::_ApplicationPtr spXlApp;
            HRESULT hr = spXlApp.CreateInstance(__uuidof(Excel::Application));
            if (FAILED(hr))
            {
                wprintf(L"CreateInstance failed w/err 0x%08lx\n", hr);
                return 1;
            }
    
            _putws(L"Excel.Application is started");
    
            spXlApp->ScreenUpdating = VARIANT_FALSE;
    
            // Create a new Workbook. (i.e. Application.Workbooks.Add)
            Excel::WorkbooksPtr spXlBooks = spXlApp->Workbooks;
            Excel::_WorkbookPtr spXlBook = spXlBooks->Add();
    
            _putws(L"A new workbook is created");
    
            // Get the active Worksheet and set its name.
            Excel::_WorksheetPtr spXlSheet = spXlBook->ActiveSheet;
    
            (void) PopulateWorksheet(spXlApp, spXlSheet, L"Report");
    
            // Save the workbook as a xlsx file and close it.
            _putws(L"Save and close the workbook");
    
            // Make the file name:
            // Get the directory of the current exe.
            wchar_t szFileName[MAX_PATH];
            if (!GetModuleDirectory(szFileName, ARRAYSIZE(szFileName)))
            {
                _putws(L"GetModuleDirectory failed");
                return 1;
            }
    
            // Concat filename "Sample1.xlsx" to the directory
            //wcsncat_s(szFileName, ARRAYSIZE(szFileName), L"Sample1.xlsx", 12);
            wcsncat_s(szFileName, ARRAYSIZE(szFileName), L"Sample1.xls", 11); // for SaveAs Excel::xlWorkbookNormal
    
            // Convert the NULL-terminated string to BSTR
            variant_t vtFileName(szFileName);
    
            spXlBook->SaveAs(vtFileName, (long) Excel::xlWorkbookNormal,
                vtMissing, vtMissing, vtMissing, vtMissing,
                Excel::xlNoChange,
                vtMissing,
                VARIANT_FALSE,
                vtMissing, vtMissing);
    
            spXlBook->Close(vtMissing, vtMissing, vtMissing);
    
            // Quit the Excel application. (i.e. Application.Quit)
            _putws(L"Quit the Excel application");
            spXlApp->ScreenUpdating = VARIANT_TRUE;
            spXlApp->Quit();
    
            _putws(L"Completed successfully");
            Sleep(2000);
        } catch (_com_error &err) {
            wprintf(L"Excel throws the error: %s\n", err.ErrorMessage());
            wprintf(L"Description: %s\n", (LPCWSTR) err.Description());
        }
    
        // Uninitialize COM for this thread.
        CoUninitialize();
    
        return 0;
    }
    
    int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    {
    	int nRetCode = 0;
    
    	HMODULE hModule = ::GetModuleHandle(NULL);
    
    	if (hModule != NULL)
    	{
    		// initialize MFC and print and error on failure
    		if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
    		{
    			// TODO: change error code to suit your needs
    			_tprintf(_T("Fatal Error: MFC initialization failed\n"));
    			nRetCode = 1;
    		}
    		else
    		{
                CreateExcelWorkbook();
    		}
    	}
    	else
    	{
    		_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
    		nRetCode = 1;
    	}
    
    	return nRetCode;
    }
    


    Graham

    Thursday, November 3, 2016 8:14 PM
  • Hi Graham F,

    you had mentioned a specific version of win10 and office.

    generally we give support for c#, vb, VBA but you are developing using c++.

    so your issue is little complex.

    so I escalate this issue to some senior engineer.

    so from now they we will try to look in this issue and try to provide you a suggestion regarding this issue.

    generally it may take some more time to get response from them so please have patients till they contact you.

    Thanks for your understanding.

    Regards

    Deepak 


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, November 4, 2016 6:18 AM
    Moderator
  • Any update on this?  It has been more than a month since the issue was escalated.


    Graham

    Friday, December 9, 2016 8:01 PM
  • Hi Graham F,

    I again make them remember regarding this issue.

    Senior engineer will try to contact you soon.

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, December 12, 2016 5:25 AM
    Moderator
  • Since a long time has gone by with no updates on this, I decided to revisit the reported problem using more recent Windows 10 builds and Office 2016 fully updated.  The good news is that the reported problem is no longer observed.  Specifically, the problem is no longer observed with Windows 10 version 1607 build 14393.1593, version 1703 build 15063.608 and version 1709 build 16288.1, the latter being a recent Windows Insider slow ring build.


    Graham

    Friday, September 22, 2017 2:49 PM